Home > Enterprise >  Filter Typescript Type based on substring key
Filter Typescript Type based on substring key

Time:09-07

Let's say we have typescript Type

type AllTypes = "hello.world"|"love.typescript"|"learn.typescript"|"love.stackoverflow"

How can I pick types from AllTypes based on substring "typescript"

CodePudding user response:

You can use the Extract<T, U> utility type to extract just those members of the AllTypes union which are assignable to an appropriate pattern template literal type (containing `${string}`, as implemented in microsoft/TypeScript#40598):

type AllTypes = "hello.world" | "love.typescript" | 
  "learn.typescript" | "love.stackoverflow";

type X = Extract<AllTypes, `${string}typescript${string}`>;
// type X = "love.typescript" | "learn.typescript"

The type `${string}typescript${string}` corresponds to all strings containing the substring "typescript", as `${string}` corresponds to any string, including the empty string.

Playground link to code

  • Related