【发布时间】:2019-04-16 00:54:07
【问题描述】:
我想键入一个只能有键“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 中使键可选?
【问题讨论】:
-
“我可以想象有更好的方法” - 不;我认为你的组合方法是最好的答案(当然也是 TypeScript 设计师的预期解决方案)
标签: typescript typescript-typings