user1365697
user1365697

Reputation: 5989

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

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

Upvotes: 17

Views: 15648

Answers (2)

Benny Code
Benny Code

Reputation: 54812

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;

Upvotes: 6

Sergeon
Sergeon

Reputation: 6788

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.

Upvotes: 20

Related Questions