Skip to content

Instantly share code, notes, and snippets.

@barthap
Created November 27, 2021 13:15
Show Gist options
  • Save barthap/d3e884dbdfa360f3a7342a29bcbee3db to your computer and use it in GitHub Desktop.
Save barthap/d3e884dbdfa360f3a7342a29bcbee3db to your computer and use it in GitHub Desktop.
Strip optional and undefined-type fields in typescript
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