Reputation: 6709
I have the following code:
enum Foo {
a,
b,
c
}
type Bar = {
[key in keyof typeof Foo]: string;
}
const test: Bar = {
a: 'a',
b: 'b'
};
The code complains that the test
variable does not have the c
property.
How can I alter the Bar
type so that the keys from the enum are optional?
Upvotes: 0
Views: 49
Reputation: 20132
The simplest solution by utility types Partial and Record
type Bar = Partial<Record<keyof typeof Foo, string>>
Upvotes: 0
Reputation: 97140
You could use a Partial<T>
:
enum Foo {
a,
b,
c
}
type Bar = Partial<{
[key in keyof typeof Foo]: string;
}>
const test: Bar = {
a: 'a',
b: 'b'
};
Or, as mentioned in the comments by @jcalz, mark the properties as optional:
enum Foo {
a,
b,
c
}
type Bar = {
[key in keyof typeof Foo]?: string;
}
const test: Bar = {
a: 'a',
b: 'b'
};
Upvotes: 1