Home > Back-end >  Filter a type to only its non-nullable attributes
Filter a type to only its non-nullable attributes

Time:01-25

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 }

CodePudding user response:

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

  •  Tags:  
  • Related