Search code examples
typescriptcastingtslinttype-assertion

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?


Solution

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