Tej
Tej

Reputation: 69

Unexpected token while adding a type to "value"

 const count= data.reduce((s:any, {(value:any)}) => s + value, 0);

i am trying to add a new type to "value" , it shows unexxected token, i am new to type script please help

Upvotes: 1

Views: 259

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

There are a couple of problems there:

  1. There shouldn't be any () around value: any part.
  2. You can't provide the type of a destructured parameter inline like that, because it conflicts with the renaming feature of destructuring syntax. {value: any} means "take the value of value and put it in the variable/parameter called any.

To give the type to a destructuring pattern, you type the pattern as a whole:

// The destructured parameter −−−−−−vvvvv
const count = data.reduce((s: any, {value}: {value: any}) => s + value, 0);
// The type for the object −−−−−−−−−−−−−−−^^^^^^^^^^^^^^

Playground link


In general, the any type annotation isn't best practice. You haven't shown what data is, but in most cases, you shouldn't have to put type annotations on the callback's parameters at all. For example, let's assume data is {value: number;}[] — an array of objects that have a value property that's a number. Given that type for data, TypeScript doesn't need any type annotations on that reduce call at all:

const count = data.reduce((s, {value}) => s + value, 0);

TypeScript knows from the 0 at the end and the definition of data that both s and value will be numbers, and that the result will be a number.


In a comment you've asked how you'd do this with forEach where you also want the index. Again, you probably don't need to specify the types, and you certainly don't need to specify the type of index since TypeScript knows what type it will be in a forEach callback. But if you did, since index isn't destructured, you just specify its type inline:

// If TypeScript knwos the type of `this.data`, you DON'T NEED THESE TYPES
this.data.forEach(({value, text, data}: {value: typeOfValue; text: typeOfText; data: typeOfData}, index: number) => {
// Types −−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−^^^^^^^^
    // ....
}

Upvotes: 2

Related Questions