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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With