1

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?

1
  • 1
    state.users have to be typed. TS doesn't now what do you store there Commented Nov 2, 2021 at 11:16

1 Answer 1

2

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}`}));
Sign up to request clarification or add additional context in comments.

Comments

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.