Reputation: 69
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
Reputation: 1073998
There are a couple of problems there:
()
around value: any
part.{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 −−−−−−−−−−−−−−−^^^^^^^^^^^^^^
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