Home > OS >  Typescript type level filtering
Typescript type level filtering

Time:02-25

I need to filter a Map type from union

type B = FilterMap<string | { a: 1 }> // { a: 1 }
type C = FilterMap<boolean | { b:2 }> // { b:2 }
type D = FilterMap<number | { c: 3 }> // { c: 3 }

is this possible?

CodePudding user response:

You can use the predefined type Exatrct, to extract any object type from a union:

type FilterMap<T> = Extract<T, object>
type B = FilterMap<string | { a: 1 }> // { a: 1 }
type C = FilterMap<boolean | { b:2 }> // { b:2 }
type D = FilterMap<number | { c: 3 }> // { c: 3 }

Playground Link

  • Related