I have such case:
interface MoverShaker {
getStatus(): { speed: number; frequency: number; };
}
function GetMoverShaker() : MoverShaker {
return {
getStatus: () => { speed: 2, frequency: 3 }
}
}
I am getting such error: The name 'frequency' does not exist in the current scope. Is such construction possible in TypeScript? If I am using such construction then everything is ok:
function GetMoverShaker(): MoverShaker {
return {
getStatus: () => {
return { speed: 2, frequency: 3 }
}
}
Set the return type of an arrow function in TypeScript # You can set the return type of an arrow function in TypeScript right after its parameters, e.g. const greet = (name: string): string => {} . Once a function's return type is set, the type checker alerts us if the function returns a value of a different type.
The most common and standard way of returning an object from an arrow function would be to use the longform syntax: const createMilkshake = (name) => { return { name, price: 499 }; }; const raspberry = createMilkshake('Raspberry'); // 'Raspberry' console.
To declare a function with an object return type, set the return type of the function to an object right after the function's parameter list, e.g. function getObj(): {name: string;} {} . If the return type of the function is not set, TypeScript will infer it.
In a type position, => defines a function type where the arguments are to the left of the => and the return type is on the right. So callback: (result: string) => any means " callback is a parameter whose type is a function.
You can add parens:
() => ({x:1,y:2})
This makes the parser understand that the { is not the beginning of a code block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With