【问题标题】:Why type casting inside object definition "doesn't work"? [closed]为什么在对象定义中进行类型转换“不起作用”? [关闭]
【发布时间】: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


【解决方案1】:
  1. 更新你的VSCode
  2. 如果您在package.json 中使用typescript 依赖项,请将其更新至 >4.6
  3. 尝试
    const store = {
        storage: {} as { [key: string]: string },
        add(value: string, key: string) {
            this.storage[key] = value
        },
        find(key: string) {
            return this.storage[key] || null
        },
    }
    

【讨论】:

  • 嗯,VS Code 建议它使用 TS 4.8.2(它是 VS Code 1.71.0),目前 package.json 中没有 typescript 依赖项@
  • 在 VS Code 1.73.0 (TS 8.4.8) 中问题仍然存在
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 2019-12-04
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 2016-09-28
  • 2013-12-05
相关资源
最近更新 更多