Home > Back-end >  Is there any TypeScript utility type to pick a property from another type and make it required?
Is there any TypeScript utility type to pick a property from another type and make it required?

Time:12-01

Right now the only way I've found is the long expression Pick...... is there any shortend I'm not aware of?

type CustomerDetailsListProps = {
  emptyValue?: string,
};

type ListItemValueProps = {
  emptyValue: Pick<Required<CustomerDetailsListProps>, 'emptyValue'>['emptyValue'],
};

CodePudding user response:

Use NonNullable:

type ListItemValueProps = {
  emptyValue: NonNullable<CustomerDetailsListProps["emptyValue"]>,
};

const a: ListItemValueProps = {} 
// Property 'emptyValue' is missing in type '{}' but required 
// in type 'ListItemValueProps'

const b: ListItemValueProps = { emptyValue: "" }

You could also use just use Required with Pick to create the whole object type in one line.

type ListItemValueProps = Required<Pick<CustomerDetailsListProps, "emptyValue">>

Playground

  • Related