Acid Coder
Acid Coder

Reputation: 2747

Typescript type level filtering

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?

Upvotes: 0

Views: 83

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249646

You can use the predefined type Extract<T, U>, 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

Upvotes: 1

Related Questions