【发布时间】:2023-02-02 23:59:42
【问题描述】:
这是一个简单的例子:
const store = {
storage: {} as { [key: string]: string },
add: function (value: string, key: string) {
this.storage[key] = value
},
find: function (key: string) {
return this.storage[key] || null
},
}
在 VS Code 中指向 storage: 显示
(property) storage: {
[key: string]: string;
}
但指向this.storage 的内部方法显示any。
我也试过
const store = {
...
} as { storage: { [key: string]: string } }
但 TS 仍然无法将 this.storage 识别为 { [key: string]: string },因此 find 的返回值的推导类型为 any。
我该怎么做才能将this.storage 识别为{ [key: string]: string }?好吧,除了为一次性实例创建一个类。
聚苯乙烯我仍然不时偶然发现这个问题,所以,虽然问题已经结束,但欢迎任何关于如何调试它的建议。这可能是 VS Code(目前我使用的是 1.74.0)的错误,因为它在 cmets 提供的游乐场中按预期工作。
【问题讨论】:
-
这有点令人困惑。你能做一个TS playground吗
-
您的问题不会在a TS playground 中复制,正确推断类型。
-
@Etheryte 哦哇,谢谢。这确实令人困惑。我会调查更多
标签: typescript visual-studio-code