I'm attempting to make a mapped type which takes all properties of a certain type and makes them optional, but leaves all others untouched. I know the optional modifier can be used when defining a mapped type, as in:
type MyPartial<T> = {
[key in keyof T]?: T[key]
}
But i'm not sure if the syntax allows this to be combined with conditions. I can get pretty close with the following:
type OptionalArrays<T> = {
[key in keyof T]: T[key] extends Array<any> ? T[key] | undefined : T[key]
}
interface Example {
foo: string[];
bar: number;
};
type Example2 = OptionalArrays<Example>;
Problem is that this results in explicit undefineds, not implicit ones, so while it will behave as i want for these two cases:
const value1: Example2 = {
foo: [],
bar: 3,
}
const value2: Example2 = {
foo: undefined,
bar: 3,
}
It will give an unwanted error that foo is missing for this one:
const value3: Example2 = {
bar: 3,
}
Is it possible to add the optional modifier (?) in a mapped type, but only when a certain condition is met?