【问题标题】:How to intentionally define an "empty interface" in typescript如何在打字稿中故意定义一个“空接口”
【发布时间】:2018-08-11 19:42:08
【问题描述】:

TypeScript 允许检查未知属性。以下

interface MyInterface {
  key: string
}

const myVar: MyInterface = {
  asda: 'asdfadf'
}

将失败,

类型 '{ asda: string; }' 不可分配给类型 'MyInterface'。
对象字面量只能指定已知属性,而 'asda' 不 存在于“MyInterface”类型中。

但是,此语句将毫无问题地编译。 Empty interface will accept any value

interface EmptyInterface {
}

const myVar: EmptyInterface = {
  asda: 'asdfadf'
}

但是,如果我真的想为可能没有 任何 属性的空对象定义类型怎么办?我怎样才能在打字稿中做到这一点?

【问题讨论】:

    标签: typescript interface


    【解决方案1】:

    要定义一个永远不会有任何成员的接口,您可以定义一个返回never的索引器

    interface None { [n: string]: never } 
    // OK
    let d2 : None = {
    
    }
    let d3 : None = {
        x: "" // error
    }
    

    【讨论】:

    • 不完全是,您仍然可以在声明为None 的变量中初始化属性,如下所示:interface None { [n: string]: never } ; function f(): never { throw new Error(); } ; const myVar: None = { q: f() }。但出于所有实际目的,never indexer 已经足够好了。
    • @artem 好的,是的,如果你有一些永远不会返回的东西,你可以将它分配给一个属性,但如果它永远不会返回,无论如何我认为它总是一个运行时错误。我也在考虑一个涵盖这个的解决方案,如果我想出任何东西我会更新:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2018-02-22
    • 2022-09-27
    • 2020-09-18
    • 1970-01-01
    • 2021-07-09
    • 2019-01-23
    相关资源
    最近更新 更多