简体   繁体   English

有没有更干净的方法从 typescript 中的箭头 function 返回 object

[英]Is there a cleaner way to return an object from an arrow function in typescript

I'm trying to return an object from an arrow function, like this function f :我正在尝试从箭头 function 返回 object,就像这样 function f

myMethod(f: data => { 
  return { someField: data.something };
});

I know that for simple types you can shrink the arrow function to just be data => data.something .我知道对于简单类型,您可以将箭头 function 缩小为data => data.something

Is this possible when you are returning an object ie something like this:当您返回 object 时,这是否可能,即:

myMethod(f: data => { someField: data.something });

That doesn't compile, I assume because the compiler thinks the { is the start of a function, not the start of an object.这不会编译,我假设是因为编译器认为{是 function 的开始,而不是 object 的开始。

Is there a syntax here which works, or should I just carry on using the longer form with the return in?这里有有效的语法吗,还是我应该继续使用较长的形式并return

You can wrap the object with parenthesis:您可以用括号括起 object:

myMethod((f: data) => ({ someField: data.something }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM