Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering union of strings with suffix

Tags:

typescript

I have this line of code:

type RouterQuery = keyof AppRouter['_def']['queries'];

Which will give me this type:

type RouterQuery = "healthz" | "post.all" | "post.byId" | "category.all" | "category.byId" | "course.all" | "course.featured"

I'm trying to get only strings that have an '.all' postfix.

The desired type would be:

type RouterQueryAll = "post.all" | "category.all" | "course.all"

How can I do that?

like image 588
Anis Draganovic Avatar asked Dec 06 '25 10:12

Anis Draganovic


1 Answers

type RouterQueryAll = Extract<RouterQuery, `${string}.all`>

Using Extract, you can ‘filter’/extract types from a union that are assignable to another type. `${string}.all` is an example of a template literal type that matches all strings ending in .all.

like image 142
cherryblossom Avatar answered Dec 09 '25 01:12

cherryblossom



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!