I want to use the keys of the union type as key of the object in typescript.
type EnumType = 'a1' | 'a2'
const object:{[key in EnumType]: string}= {
a1: 'test'
}
In this case I have to add even a2 as a key in the object. Is there a way to make this optional?
Playground
Just add a question mark like this:
type EnumType = 'a1' | 'a2'
const object:{[key in EnumType]?: string}= {
a1: 'test'
}
The object
definition with your current code:
const object: {
a1: string;
a2: string;
}
Becomes:
const object: {
a1?: string | undefined;
a2?: string | undefined;
}
Allowing every key to be optional.
please use Utility Types
type EnumType = "a1" | "a2";
const object: Partial<Record<EnumType, string>> = {
a1: "test",
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With