Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Last active June 19, 2019 20:01
Show Gist options
  • Save Willmo36/9a47f24abd457fc511b3f8a43b228f81 to your computer and use it in GitHub Desktop.
Save Willmo36/9a47f24abd457fc511b3f8a43b228f81 to your computer and use it in GitHub Desktop.
Replace required `| undefined` keys with unrequired keys
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type OptionalKeys<T> = Exclude<{
[K in keyof T]: Extract<T[K], undefined> extends never ? never : K;
}[keyof T], undefined>;
type UndefinedToUnrequired<T> = {
[K in OptionalKeys<T>]?: T[K]
} & Omit<T, OptionalKeys<T>>
type UndefinedToUnrequired2<T> =
Partial<Pick<T, OptionalKeys<T>>> & Omit<T, OptionalKeys<T>>
//------------USAGE---------------
type Max = {
optional: string | undefined;
optional2?: boolean;
required: number;
}
type Max2 = UndefinedToUnrequired<Max>;
//have to specify keys
const m1: Max = {
optional: undefined,
optional2: undefined,
required: 123
}
const m2: Max2 = {
required: 123
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment