Jib*_*mas 12 javascript types typescript
我想使用联合类型的键作为打字稿中对象的键。
type EnumType = 'a1' | 'a2'
const object:{[key in EnumType]: string}= {
a1: 'test'
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我什至必须添加 a2 作为对象中的键。有没有办法让它成为可选的?
Twi*_*her 24
只需添加一个问号,如下所示:
type EnumType = 'a1' | 'a2'
const object:{[key in EnumType]?: string}= {
a1: 'test'
}
Run Code Online (Sandbox Code Playgroud)
object您当前代码的定义:
const object: {
a1: string;
a2: string;
}
Run Code Online (Sandbox Code Playgroud)
变成:
const object: {
a1?: string | undefined;
a2?: string | undefined;
}
Run Code Online (Sandbox Code Playgroud)
允许每个键都是可选的。
小智 17
请使用实用程序类型
type EnumType = "a1" | "a2";
const object: Partial<Record<EnumType, string>> = {
a1: "test",
};
Run Code Online (Sandbox Code Playgroud)