Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Typescript Type based on substring key

Tags:

typescript

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"

like image 313
Forte Zhuo Avatar asked Apr 08 '26 06:04

Forte Zhuo


1 Answers

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

like image 198
jcalz Avatar answered Apr 10 '26 04:04

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!