Issue
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"
Solution
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.
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.