Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript exclude optional fields from type

There is the Utility type NonNullable which will remove undefined and null values from a union type. But I was wondering if there was a way to remove optional fields from a type.

Basically if I have a type like this:

type MyType = {
  thingOne: number,
  thingTwo?: number
};

I want to be able to create a type out of the required fields only

type MyRequireds = NonOptional<MyType>;
// which is a type only containing "thingOne"

Is there some utility class that would satisfy the made up "NonOptional" utility class?

like image 212
Jake Avatar asked Sep 10 '25 15:09

Jake


1 Answers

A tricky solution:

type RequiredKeys<T> = {
  [K in keyof T]: ({} extends { [P in K]: T[K] } ? never : K)
}[keyof T];

type NonOptional<T> = Pick<T, RequiredKeys<T>>;

type MyType = {
  thingOne: number,
  thingTwo?: number
};

type MyRequireds = NonOptional<MyType>;

Playground

The trick is that {} extends {thingTwo?: number} but doesn't extend {thingOne: number}. I originally found this solution here.

like image 115
Valeriy Katkov Avatar answered Sep 13 '25 07:09

Valeriy Katkov