简体   繁体   中英

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

TSLint marks both of these as errors:
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:

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

This pairs well with object destructuring:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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