英文:
How to create Record with dynamic string union property names that are optional?
问题
我想定义一种对象类型,其中属性名称是预定义的,但也是可选的。
我想创建下面更长的语法的等价物,但是否有一种方法使它具有可选属性,以便我可以轻松添加/删除这些选项?
interface List {
one?: string;
two?: string;
three?: string;
}
我正在尝试找到一种使以下无效代码生效的方法。
type options = 'one' | 'two' | 'three';
type List = Record<options, string>;
// 有效
const MyObjOne: List = {
one: 'Value 1',
two: 'Value 2',
three: 'Value 3',
}
// 无效
const MyObjTwo: List = {
one: 'Value 1',
two: 'Value 2',
}
但是 TypeScript 对 MyObj
给出以下错误 TS Playground 链接:
Property 'three' is missing in type '{ one: string; two: string; }' but required in type 'List'.
英文:
I want to define an object type where the property names are pre-defined, but also optional.
I want to create the equivalent of the below longer syntax, but is there a way to make it dynamic with optional properties so I could easily add / remove those options?
interface List {
one?: string;
two?: string;
three?: string;
}
I'm trying to find a way to make the following invalid code work.
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',
}
But TypeScript gives this error for MyObj
TS Playground link
Property 'three' is missing in type '{ one: string; two: string; }' but required in type 'List'.
答案1
得分: 1
使用实用程序类型Partial
:
type List = Partial<Record<options, string>>;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论