简体   繁体   中英

Typescript Object is of Type Unknown, firebase functions

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.

force the type as:

const token: string = value.token;

or

const token = value.token as string;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM