Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a type to only its non-nullable attributes

Tags:

typescript

given this type

type HasOptionals = {
   name: string
   surname?: string
}

is it possible to generate a type that excludes any optional properties?

type example = OnlyRequired<HasOptionals> // { name: string }
like image 573
stackoverfloweth Avatar asked Mar 18 '26 23:03

stackoverfloweth


1 Answers

You can use a mapped type with key remapping:

type OnlyRequired<T> = {
    [K in keyof T as undefined extends T[K] ? never : K]: T[K]
}

Now OnlyRequired<HasOptionals> is indeed { name: string; }.

like image 96
jonrsharpe Avatar answered Mar 20 '26 14:03

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!