I have a variable foo
to be initialized. My attempt below does not compile.
let foo: (x: number)=>{y:number,z: number}= (x)=>{x 1,x 2};
with the following error:
Left side of comma operator is unused and has no side effects.ts(2695) (parameter) x: number
Question
What is the correct way to initialize the variable foo
?
CodePudding user response:
Because of how arrow function notation works, the curly braces around the output are interpreted as containing the function body instead of a value being returned.
It also looks like you've forgot to add the y
and z
labels in your output.
Try this:
let foo: (x: number) => {y: number, z: number} = (x) => {
return {y: x 1, z: x 2};
};
It's also worth noting that when initialising a variable in this way, TypeScript is able to infer its type. So you can actually shorten your code to just this:
let foo = (x: number) => {
return {y: x 1, z: x 2};
};