简体   繁体   English

如何指定文字类型 object 并遵守 TSLint?

[英]How to specify type of literal object and comply with TSLint?

TSLint marks both of these as errors: TSLint 将这两个标记为错误:
const a = {} as MyClass; // no-object-literal-type-assertion
const a = <MyClass>{}; // no-angle-bracket-type-assertion

And advices to use explicit typing:以及使用显式类型的建议:
let a: MyClass

But what should you use when just using literals and not assignments?但是当只使用文字而不是赋值时你应该使用什么?
return { name: 'john' } as MyClass
return <MyClass> { name: 'john' }

What alternative can be used there without declaring a variable?在不声明变量的情况下可以使用什么替代方法?

You can place explicit interface definitions inline.您可以内联放置显式接口定义。 Starting with the example:从示例开始:

interface IGuy {
  name: string;
  age: number;
}
const guy: IGuy = {name: 'N', age: 1 };

With a slight alteration to the format, we can place that same interface inline, explicitly and anonymously:通过对格式稍作改动,我们可以将相同的接口显式和匿名地内联:

const guy: { name: string, age: number } = {name: 'N', age: 1 };

It also works in function signatures:它也适用于 function 签名:

myFunction(guy: { name: string, age: number)) { //

This pairs well with object destructuring:这与 object 解构很好地配对:

myFunction({ name, age }: { name: string, age: number) { //

If your output return value matches the function return signature, you should be OK, if this is OK to you:如果你的 output 返回值匹配 function 返回签名,你应该没问题,如果这对你来说没问题:

function myFunction(): { name: string, age: number} {
  return { name: 'N', age: 1 };
}

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

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