简体   繁体   English

为什么我在对象文字上出现错误类型断言被禁止,而是使用类型注释。 tslint(no-object-literal-type-assertion)?

[英]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我在 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我收到错误类型断言对象文字被禁止,请改用类型注释。 tslint(no-object-literal-type-assertion

This rule forbids the use of as to annotate types. 此规则禁止使用as来注释类型。 Instead, you should use the type annotation var: type syntax, as in:相反,您应该使用类型注释var: type语法,如下所示:

    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):在某些情况下,该语法可能会引发一些错误,然后您可能需要将对象文字转换为any with as any (规则实际上允许):

    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.如果是这样,这取决于您的 tslint 配置,如果您的配置不标准,您可能需要提供一些额外信息。 If it is, you must go to the tslint.json file an add:如果是,则必须转到tslint.json文件添加:

no-object-literal-type-assertion: false

to the rules field of the json.到json的rules字段。

You can bypass the no-object-literal-type-assertion rule by casting your object to unknown before assigning it to another type.在将对象分配给其他类型之前,您可以通过将对象强制转换为unknown来绕过no-object-literal-type-assertion规则。

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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