【发布时间】:2022-03-08 19:29:18
【问题描述】:
我想让MyInterface.dic像字典一样name: value,我定义如下:
interface MyInterface {
dic: { [name: string]: number }
}
现在我创建一个等待我的类型的函数:
function foo(a: MyInterface) {
...
}
然后输入:
let o = {
dic: {
'a': 3,
'b': 5
}
}
我期待foo(o) 是正确的,但编译器正在下降:
foo(o) // Typescript error: Index signature is missing in type { 'a': number, 'b': number }
我知道有一个可能的转换:let o: MyInterface = { ... } 可以解决问题,但问题是,为什么 typescript 无法识别我的类型?
额外:如果 o 被声明为内联,则可以正常工作:
foo({
dic: {
'a': 3,
'b': 5
}
})
【问题讨论】:
-
目前看来,这个确切的代码在 Typescript 中传递没有任何问题:typescriptlang.org/play?#code/…
标签: casting typescript