1

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;
};
4
  • Didn't get it. interface allColors is the same as type allColors. Commented May 14, 2020 at 2:25
  • @qxg the type doesn't require all of those properties, whereas the interface would require all of them to be set. Commented May 14, 2020 at 2:28
  • 1
    It works as expected for me (v3.9.2): typescriptlang.org/play/#code/… Commented May 14, 2020 at 2:40
  • @Soc is right. This works as expected. Make sure you have "strict": true in tsconfig.json compilerOptions and are running a relatively recent version of TypeScript Commented May 14, 2020 at 3:20

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.