You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用String类型变量访问对象时TypeScript报错的解决办法

解决TypeScript索引类型报错问题

核心原因

你用了大写的String作为display的类型,这是TypeScript里的包装对象类型,而对象索引只允许使用原始类型(string/number/symbol),所以编译器抛出报错。

解决方法

方法1:改用原始类型string

直接把display的类型从String改成小写的string,这是最直接的修复方式:

const props = defineProps<{
    sentence: Sentence,
    display: string,
}>()

方法2:更严格的类型约束(推荐)

如果Sentence类型的键是固定集合,可以把display的类型定义为keyof Sentence,这样既能消除报错,还能保证display一定是sentence存在的键,避免无效索引:

const props = defineProps<{
    sentence: Sentence,
    display: keyof Sentence,
}>()

修改后,sentence[display]的TypeScript报错会消失,同时完全保留原有代码逻辑。

内容的提问来源于stack exchange,提问作者Jolly Boy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:12:33