【发布时间】:2021-07-07 20:15:11
【问题描述】:
我有一些通用接口:
interface IProps<T> {
item: T;
key: keyof T;
}
如何确保item[key] 是字符串或数字类型,以便item[key] 可用于索引Record<string | number, string>?
我正在使用 typescript v3.9
【问题讨论】:
-
是的,但我更新了问题,使其更具体
-
所以现在它是 p̶o̶s̶s̶i̶b̶l̶e̶d̶u̶p̶l̶i̶c̶a̶t̶e̶̶o̶f̶ 与 TypeScript: Accept all Object keys that map to a specific type alth 相关,其中代码示例类似于 this。那对你有用吗?另请注意,构成人们可以测试的minimal reproducible example 有助于您的代码;实际上,如果
item是特定类型,item[key]可以索引Record<string | number, string>。代码中的单元测试用例会阻止多轮修改。
标签: typescript typescript-generics