typescript - 为 Typescript Record 定义可选键列表

标签 typescript typescript-typings

我想输入一个只能有键“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/

相关文章:

javascript - 单击按钮以升序/降序对 Angular 中的数据进行排序

javascript - 通过这个简单的示例了解 Promise 链

javascript - 类型和实现它的类的命名约定是什么?

javascript - 只能包含特定列表中的元素的数组的 typescript 类型

node.js - 使用 Fabric Node SDK 将新组织添加到现有的 Hyperledger Fabric 网络

TypeScript 接口(interface)和实现

typescript - 使用可选重载时的剩余参数

typescript - Vue + TypeScript 覆盖 `export default Vue`

typescript - 无法使用 typescript 将选项对象添加到 SHA3 函数

typescript : 'RegExpMatchArray' 类型的参数不可分配给 'string' 类型的参数