简体   繁体   中英

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM