如何故意在打字稿中定义一个"空接口"

Ton*_*ony 1 interface typescript

TypeScript允许检查是否检查未知属性.下列

interface MyInterface {
  key: string
}

const myVar: MyInterface = {
  asda: 'asdfadf'
}
Run Code Online (Sandbox Code Playgroud)

会失败的

输入'{asda:string; }'不能赋值为'MyInterface'.
对象文字只能指定已知属性,'myInterface'类型中不存在'asda'.

但是,此语句将编译没有任何问题.空接口将接受任何值

interface EmptyInterface {
}

const myVar: EmptyInterface = {
  asda: 'asdfadf'
}
Run Code Online (Sandbox Code Playgroud)

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

Tit*_*mir 5

要定义从不拥有任何成员的接口,可以定义返回的索引器 never

interface None { [n: string]: never } 
// OK
let d2 : None = {

}
let d3 : None = {
    x: "" // error
}
Run Code Online (Sandbox Code Playgroud)