定义Typescript记录的可选键列表

定义Typescript记录的可选键列表,typescript,typescript-typings,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<Recor

我想键入一个只能有键“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>>;
类型列表=部分;

这是可行的,但我可以想象有一个更好的方法来做到这一点,而不需要部分。是否有其他方法使记录内的键成为可选的?

无法指定
记录的成员的可选性。它们是定义所要求的

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 PartialList = Partial<List>;

看起来在新版本的typescript中,您可以执行以下操作

type YourUnion = 'a' | 'b' | 'c';   
type ObjectWithOptionalKeys = Partial<Record<YourUnion, string>>
const someObject: ObjectWithOptionalKeys {
  a: 'str', // works
  b: 1 // throws
}
// c may not be specified at all
键入YourUnion='a'|'b'|'c';
键入ObjectWithOptionalKeys=Partial
const someObject:带有可选键的对象{
a:'str',//有效
b:1//
}
//c可能根本没有指定

除了部分解决方案之外, 也许有一个更明显的选择要考虑。

相反,您可以将数据存储在地图中

const map: Map<KeyType, ValueType> = new Map();
const-map:map=newmap();
从功能角度看,没有太大区别。
这实际上取决于上下文,这是否是一个可行的替代方案。

“无法指定
记录的成员的可选性。”。。。你对此有把握吗<代码>部分
就我所知,似乎就是这样运作的。这是自回答后发生的变化吗?@KOVIKO
Partial
是另一种类型,问题是您是否可以为
Record
本身指定它。最后一个代码片段显示了使用
Record
组合
Partial
的能力,以获得
PartialRecord
的效果。啊,我现在明白了,他们特别询问如何不使用Partial,我对第一句话读得太多了。mb录制<代码>怎么样?它不需要指定所有可能的字符串。为什么会出现不一致?是否可以指定哪些字段是可选的,哪些字段不用于记录?“我可以想象有更好的方法”-否;我认为你的写作方法是最好的答案(当然也是打字机设计者想要的解决方案)
type PartialList = Partial<Record<'a' | 'b' | 'c', string>>;
type List = {
    a?: string;
    b?: string;
    c?: string;
}
type YourUnion = 'a' | 'b' | 'c';   
type ObjectWithOptionalKeys = Partial<Record<YourUnion, string>>
const someObject: ObjectWithOptionalKeys {
  a: 'str', // works
  b: 1 // throws
}
// c may not be specified at all
const map: Map<KeyType, ValueType> = new Map();