1

I have a problem with a function for firebase functions, written in typescript.

first I have some background info:

the data structure of the /tokens ref of the realtime database:

Tokens: [
     TOKENS_ID: {
           token: String
},
]

the following code is giving me compiling errors:

export const onBlogPost = functions.database.ref("/blogs/{bid}")
.onCreate((blogData) => {
  console.log(JSON.stringify(blogData.val()));
  admin.database().ref("/tokens").once("value")
      .then((snapshot) => {
        const data = snapshot.val();
        const tokens = Object.values(data).map((value) => {
          console.log(JSON.stringify(value));
          const token = value.token;
          return token;
        });
        return console.log(JSON.stringify(tokens));
      });
});

The problem is within the .then((snapshot) => {...} part. the goal of this part of the code is to transform all the objects within the data snapshot to a single array of just the tokens.

the compiling error occurs on the row with the following code:

const token = value.token;

the compiling error is as follows:

src/index.ts(14,29): error TS2571: Object is of type 'unknown'.

What is the correct solution to this, I have tried to assign a type to the variable value in map() but that was failing horendesly.

1 Answer 1

1

force the type as:

const token: string = value.token;

or

const token = value.token as string;
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried both, but none of them seems to work
then force to parse the value as: const token: string = JSON.parse(JSON.stringify(value.token)). This must work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.