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 }
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; }.
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