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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With