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

Time:08-11

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:

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

CodePudding user response:

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

  • Related