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

TypeScript中如何为不定属性对象添加值为字符串的类型注解

正确的TypeScript类型注解写法

要确保Definitions对象的每个属性值都是字符串,你需要使用索引签名来定义类型,以下是两种可行的写法:

写法一:直接使用索引签名

var Definitions: { [key: string]: string } = {
    "eat": "put (food) into the mouth and chew and swallow it",
    "drink": "take (a liquid) into the mouth and swallow.",
    "fly": "move through the air using wings."
}

这里[key: string]: string表示对象的键是任意字符串类型,对应的值必须是字符串类型,完全匹配你的需求。

写法二:先定义类型别名/接口再使用

如果需要复用这个类型,可以先定义类型别名或接口:

// 类型别名
type Dictionary = { [key: string]: string };

// 或者接口
interface Dictionary {
    [key: string]: string;
}

var Definitions: Dictionary = {
    "eat": "put (food) into the mouth and chew and swallow it",
    "drink": "take (a liquid) into the mouth and swallow.",
    "fly": "move through the air using wings."
}

你之前写法的问题说明

  • {...string[]}是无效语法,TypeScript不支持这种写法描述对象结构;
  • {words:...string[]}同样错误,...无法用来定义对象属性的类型,且结构和你的实际对象不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:05:26