【发布时间】:2023-02-06 18:18:19
【问题描述】:
我想定义一个对象类型,其中属性名称是预定义的,但也是可选的。
我想创建等同于以下较长语法的语法,但有没有办法通过可选属性使其动态化,以便我可以轻松添加/删除这些选项?
interface List {
one?: string;
two?: string;
three?: string;
}
我试图找到一种方法来使以下无效代码起作用。
type options = 'one' | 'two' | 'three';
type List = Record<options, string>;
// Valid
const MyObjOne: List = {
one: 'Value 1',
two: 'Value 2',
three: 'Value 3',
}
// Invalid
const MyObjTwo: List = {
one: 'Value 1',
two: 'Value 2',
}
但是 TypeScript 为 MyObj TS Playground link 给出了这个错误
Property 'three' is missing in type '{ one: string; two: string; }' but required in type 'List'.
【问题讨论】:
标签: typescript types index-signature