简体   繁体   中英

How to declare typescript type within a js array map?

I am trying to make the following mapping with the js array map function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

x =  state.users.map(({id, firstName, lastName}) => 
    ({id, value: `${firstName} ${lastName}`}));

However, I am getting the following typescript error Binding element 'X' implicitly has an any type for each of the properties eg id, firstname etc

If I try to assign a type to the properties like so:

x =  state.users.map(({id: number, firstName: string, lastName: string}) => 
    ({id, value: `${firstName} ${lastName}`}));

these are allocated as values not types.

How can I correctly assign a type to a property within a map function?

You can put any:

x =  state.users.map(({id, firstName, lastName}: any) => 
    ({id, value: `${firstName} ${lastName}`}));

or with an explicit type:

x =  state.users.map(({id, firstName, lastName}: {id: string, firstName: string, lastName: string}) => 
    ({id, value: `${firstName} ${lastName}`}));

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