tyescript 中使用 interface 做类型映射报错而换成 type 定义就可以了?
如上图所示遇到个奇葩的问题使用 interface 定义映射报错,然而使用 type 同样的定义方式没有问题,使用的 typescript 版本是 "typescript": "^4.6.3"。这个是什么原因导致的呢,是哪里出现了问题呢?
回复
1个回答

test
2024-06-23
因为 interface
不支持这种写法,索引签名 - index signature
的写法是 [key: <string | number | symbol等等>]
.
可以看看 index signature 中的说明.
所以你的那个写法还可以改成这样:
interface ActionType {
[key: string]: typeof INITIAL_STATE[keyof typeof INITIAL_STATE]
}
let demo: ActionType = {
name: [1, 2, 3],
age: 20,
gender: ["male", "female"],
};
console.log(demo);
/**
* { name: [ 1, 2, 3 ], age: 20, gender: [ 'male', 'female' ] }
*/
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容