Last active
June 19, 2019 20:01
-
-
Save Willmo36/9a47f24abd457fc511b3f8a43b228f81 to your computer and use it in GitHub Desktop.
Replace required `| undefined` keys with unrequired keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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