Home > Net >  "Remove" alternatives of union type of anonymus objects
"Remove" alternatives of union type of anonymus objects

Time:11-02

I have union types with a know discriminator field, in this case disc. These union types are unions of object literals, and other than the discriminator field they can have arbitrary fields, for example:

type Union =
  | { disc: "a"; someField: string }
  | { disc: "b"; some: boolean; field: number }
  | { disc: "c"; foo: number }
  | { disc: "d" };

How could I make a generic type, that "removes" some union alternatives, based on the disc (discriminator) field? Is this possible with TypeScript?

Eg.:

type SomeTypeTransform<Type, Keys> = ???

type UnionWithoutCAndD = SomeTypeTransform<Union, "c" | "d">

type CAndDManuallyRemoved =
  | { disc: "a"; someField: string }
  | { disc: "b"; some: boolean; field: number }

// I'd like UnionWithoutCAndD to be equivalent with CAndDManuallyRemoved 

CodePudding user response:

It's actually already built-in (as Exclude), but you need a little more magic:

type SomeTypeTransform<Type, Keys> = Exclude<Type, { disc: Keys }>;

From the docs:

Exclude<UnionType, ExcludedMembers>

Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers`.

Playground

  • Related