TypeScript 函数箭头表达式返回对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12809285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript function arrow expression returning object
提问by Dace Zarina
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:
我收到这样的错误:当前范围中不存在名称“频率”。这样的构造在 TypeScript 中可行吗?如果我使用这样的结构,那么一切都很好:
function GetMoverShaker(): MoverShaker {
return {
getStatus: () => {
return { speed: 2, frequency: 3 }
}
}
回答by Roger Johansson
You can add parens:
您可以添加括号:
() => ({x:1,y:2})
This makes the parser understand that the { is not the beginning of a code block.
这使解析器明白 { 不是代码块的开始。

