TypeScript function arrow expression returning object

Typescript

Typescript Problem Overview


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 }
        }
}

Typescript Solutions


Solution 1 - Typescript

You can add parens:

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

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

Solution 2 - Typescript

In your first statement you do not return an object. If you want to disregard the return keyword in an arrow function that returns an object you will need to wrap the directly returned value in ().

Which will make your function look like this instead

function GetMoverShaker() : MoverShaker {
    return {
        getStatus: () => ({ speed: 2, frequency: 3 })
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDace ZarinaView Question on Stackoverflow
Solution 1 - TypescriptRoger JohanssonView Answer on Stackoverflow
Solution 2 - TypescriptClaus Marin KaiserView Answer on Stackoverflow