简体   繁体   English

如何在打字稿中有意定义“空接口”

[英]How to intentionally define an “empty interface” in typescript

TypeScript allows checking for checking unknown properties. TypeScript允许检查未知属性。 The following 下列

interface MyInterface {
  key: string
}

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

will fails with 将失败

Type '{ asda: string; 输入'{asda:string; }' is not assignable to type 'MyInterface'. }”不可分配给“ MyInterface”类型。
Object literal may only specify known properties, and 'asda' does not exist in type 'MyInterface'. 对象文字只能指定已知的属性,而“ MyInterface”类型中不存在“ asda”。

However, this statement will compile without any issue. 但是,此语句将编译没有任何问题。 Empty interface will accept any value 空接口将接受任何值

interface EmptyInterface {
}

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

However, what if I actually want to define type for an empty object that may not have any properties? 但是,如果我实际上想为可能没有任何属性的空对象定义类型呢? How can I accomplish that in typescript? 如何在打字稿中完成?

To define an interface that never has any members, you can define an indexer that returns never 要定义一个永不包含任何成员的接口,您可以定义一个返回never索引的索引器

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

}
let d3 : None = {
    x: "" // error
}

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

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