根据 Typescript 文档,当使用对象字面量时,它应该与接口(interface)完全匹配。但是对于以下代码,playground 没有显示任何错误信息:
这里的 prop 是字符串,所以它与 [index: number]: number
冲突,这意味着索引应该是一个数字,该索引处的值应该是一个数字,对于 以外的属性姓名
和年龄
。
这是一个错误吗?如果我错了,请解释这是如何工作的?
最佳答案
您总是可以指定比接口(interface)要求更多的属性。作为演示,请看一下这段代码:( or on the playground )
// index.ts
interface MyInterface {
obligatoryProperty: string
optionalProperty?: string
[index: number]: number
}
let impl1: MyInterface = {} // fails compilation
let impl2: MyInterface = { obligatoryProperty: 'hello' } // compiles fine
let impl3: MyInterface = {
obligatoryProperty: 'hello',
optionalProperty: 'hello',
2: 2,
3: 3,
notSpecifiedPropertyThatIsAlsoNotANumber: 'hello',
} // Still fine
关于 typescript 编译器不显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39079314/