Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript function arrow expression returning object

Tags:

typescript

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 }
        }
}
like image 786
Dace Zarina Avatar asked Oct 09 '12 22:10

Dace Zarina


People also ask

How do I return an object from arrow function in TypeScript?

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.

How do you return an object from arrow?

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.

How do you return an object in TypeScript?

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.

What => means in TypeScript?

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.


1 Answers

You can add parens:

() => ({x:1,y:2})

This makes the parser understand that the { is not the beginning of a code block.

like image 180
Roger Johansson Avatar answered Oct 12 '22 18:10

Roger Johansson