我希望MyInterface.dic像字典一样name: value,我将其定义如下:
interface MyInterface {
dic: { [name: string]: number }
}
Run Code Online (Sandbox Code Playgroud)
现在我创建一个等待我的类型的函数:
function foo(a: MyInterface) {
...
}
Run Code Online (Sandbox Code Playgroud)
并输入:
let o = {
dic: {
'a': 3,
'b': 5
}
}
Run Code Online (Sandbox Code Playgroud)
我期待foo(o)是正确的,但编译器正在下降:
foo(o) // Typescript error: Index signature is missing in type { 'a': number, 'b': number }
Run Code Online (Sandbox Code Playgroud)
我知道有一个可能的演员:let o: MyInterface = { ... }哪个可以做,但问题是,为什么打字稿不能识别我的类型?
额外:如果o内联声明,则工作正常:
foo({
dic: {
'a': 3,
'b': 5
}
})
Run Code Online (Sandbox Code Playgroud)