简体   繁体   中英

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

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.

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;

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