Record<Keys, Type>
用于构造一个对象类型,其属性键为Keys
,属性值为Type
。该实用程序可用于将一种类型的属性映射到另一种类型。 这在声明一个key-value
类型时很有帮助。
ts
type MyRecord = Record<string, number>;
const myObject: MyRecord = {
key1: 10,
key2: 20,
};
type MyRecord = Record<string, number>;
const myObject: MyRecord = {
key1: 10,
key2: 20,
};
可替代的:
ts
type Dictionary = { [key: string]: number };
type Dictionary = { [key: string]: number };
或者全局声明:
ts
declare global {
type Dictionary<T> = { [key: string]: T };
}
declare global {
type Dictionary<T> = { [key: string]: T };
}
相关参考:
TypeScript: Documentation - Utility Types
node.js - No index signature with a parameter of type 'string' was found on type - Stack Overflow