我想输入一个只能有键“a”、“b”或“c”的对象。
所以我可以这样做:
Interface IList {
a?: string;
b?: string;
c?: string;
}
它们都是可选的!
现在我想知道这是否可以用 Record
写成一行
type List = Record<'a' | 'b' | 'c', string>;
唯一的问题是需要定义所有键。所以我最终得到了
type List = Partial<Record<'a' | 'b' | 'c', string>>;
这行得通,但我可以想象有更好的方法可以在不使用 Partial 的情况下做到这一点。有没有其他方法可以使 Record 中的键可选?
最佳答案
无法指定Record
成员的可选性。它们是定义所必需的
type Record<K extends keyof any, T> = {
[P in K]: T; // Mapped properties are not optional, and it's not a homomorphic mapped type so it can't come from anywhere else.
};
如果这是您的常见情况,您可以定义自己的类型:
type PartialRecord<K extends keyof any, T> = {
[P in K]?: T;
};
type List = PartialRecord<'a' | 'b' | 'c', string>
或者您也可以使用预定义的映射类型定义 PartialRecord
:
type PartialRecord<K extends keyof any, T> = Partial<Record<K, T>>
关于typescript - 为 Typescript Record 定义可选键列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53276792/