Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I conditionally add multiple properties to an object type based on a generic union?

Given this union type:

type Union = "a" | "b";

How can I add multiple new keys to an object type? I know I can do this with a single condition:

type Condition<T extends Union> = {
  [K in T extends "a" ? "someProp" : never]: string;
}

type Result = Condition<"a">;

// type Result = {
//   someProp: string;
// }

But when I try to add another key with a condition as well I get a syntax error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type Condition<T extends Union> = {
  [K in T extends "a" ? "someProp" : never]: string;
  [K in T extends "a"? "anotherProp": never]: string;
//        ~~~~~~~      ~~~~~~~~~~~~        ~
}

Why can’t I just do two simple checks there?

TypeScript Playground

>Solution :

You can use a union in the condition in the index signature:

type Union = "a" | "b";

type Condition<T extends Union> = {
  [K in T extends "a" ? "someProp" | "anotherProp" : never]?: string;
}

const a: Condition<"a"> = {
  someProp: "foo",
  anotherProp: "foo",
}

TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading