【问题标题】:Typescript did not show error even I did not implement all the compulsory properties of an interface即使我没有实现接口的所有强制属性,Typescript 也没有显示错误
【发布时间】:2021-03-02 10:43:16
【问题描述】:
interface Test {
    foo: string;
    bar: string;
}

const obj = {
    foo: 'ok'
} as Test;

即使我没有在obj 中实现bar,Typescript 编译器也没有提示我错误。我希望上面的示例会显示错误,因为bar 不是可选属性。我可以知道怎么来吗?提前致谢。同时,下面的演示也让我感到困惑。 obj 只实现了Test,这意味着它应该只包含foobar。但是,当我另外添加zar时,也没有提示错误。

interface Test {
    foo: string;
    bar: string;
}

const obj = {
    foo: 'ok',
    bar: 'ok',
    zar: 'expected not ok'
} as Test;

【问题讨论】:

    标签: typescript interface typing


    【解决方案1】:

    请查看这些人对as 做什么What does the "as" keyword do? 的回答。

    因此 as 关键字告诉编译器通过强制执行将其视为您的类型,因此请尝试在下面执行此操作:

    interface Test {
        foo: string;
        bar: string;
    }
    
    const obj: Test = {
        foo: 'ok'
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 2020-07-30
      • 2022-10-15
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      相关资源
      最近更新 更多