Home > other >  How to declare typescript type within a js array map?
How to declare typescript type within a js array map?

Time:11-03

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 e.g. 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?

CodePudding user response:

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}`}));
  • Related