d-_-b
d-_-b

Reputation: 23161

Typescript create a type with required keys from another type

I have the following type defined:

export type colors = "red" | "blue" | "green"

export interface details {
   name: string;
   id: string;
}

Is there a way to define a type object that requires all 3 to be defined, without having to loop through each explicitly?

export interface allColors {
   red: details;
   blue: details;
   ... etc.
}

as opposed to this type which makes the keys optional?

export type allColors =  {
    [key in colors]: details;
};

Upvotes: 1

Views: 1742

Answers (1)

Wong Jia Hau
Wong Jia Hau

Reputation: 3069

You can achieve this by using type alias and Record type.

export type colors = "red" | "blue" | "green"

export interface details {
   name: string;
   id: string;
}

export type allColors = Record<colors, details> 

// Usage
const x: allColors = { // type error, missing properties: 'blue', 'green'
  red: {
    name: 'red',
    id: '1'
  }
}

Suppose you want to override the type of certain keys, say you want green: number instead of green: details, you can achieve this using Exclude and Intersection Types:

export type allColors = Record<Exclude<colors, 'green'>, details> & {green: string}

// Usage
const x: allColors = { 
  red: {
    name: 'red',
    id: '1'
  },
  green: 'hello' // No error
}

Upvotes: 5

Related Questions