Created
November 27, 2021 13:15
-
-
Save barthap/d3e884dbdfa360f3a7342a29bcbee3db to your computer and use it in GitHub Desktop.
Strip optional and undefined-type fields in typescript
This file contains 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 NonNullableKeys<T extends object> = { | |
[K in keyof T]: T[K] extends NonNullable<T[K]> ? K : never; | |
}[keyof T]; | |
type NonOptionalKeys<T extends object> = { | |
[K in keyof T]-?: {} extends Pick<T, K> ? never : K; | |
}[keyof T]; | |
type OnlyDefinedFields<T extends object> = Pick<T, NonNullableKeys<T>>; | |
type A = { | |
a: string; | |
b: string | undefined; | |
c?: string; | |
} | |
type B = NonNullableKeys<A>; // "a" | |
type C = NonOptionalKeys<A>; // "a" | "b" | |
type D = OnlyDefinedFields<A>; // { a: string } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment