Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I got an error type assertion on object literals is forbidden, use a type annotation instead.tslint(no-object-literal-type-assertion)?

Tags:

typescript

I have code in TS

interface Context {
    out: vscode.OutputChannel,
    myPorts: number[]
}

const outputChannel = vscode.window.createOutputChannel('my-run');

    const ctx = {
        out: OutputChannel,
        myPorts: []
    } as Context;

I got error Type assertion on object literals is forbidden, use a type annotation instead.tslint(no-object-literal-type-assertion

like image 386
user1365697 Avatar asked May 16 '19 10:05

user1365697


2 Answers

You can bypass the no-object-literal-type-assertion rule by casting your object to unknown before assigning it to another type.

Example:

const ctx = {
  out: OutputChannel,
  myPorts: []
} as unknown as Context;
like image 167
Benny Neugebauer Avatar answered Sep 23 '22 15:09

Benny Neugebauer


This rule forbids the use of as to annotate types. Instead, you should use the type annotation var: type syntax, as in:

    const ctx: Context = {
        out: OutputChannel,
        myPorts: []
    };

That syntax may throw some errors in some cases and then you may need to cast the object literal to any with as any (which is actually allowed by the rule):

    const ctx: Context = {
        out: OutputChannel,
        myPorts: []
    } as any;

Now, I'm not sure if your asking about how to get your code to comply with the rule (I already answered that), or why the warning appears in the first place. If so, this depends on your tslint configuration, and you may need to provide some extra info if your configuration is not standard. If it is, you must go to the tslint.json file an add:

no-object-literal-type-assertion: false

to the rules field of the json.

like image 28
Sergeon Avatar answered Sep 25 '22 15:09

Sergeon