#Match/filter strings from string literal union that match criteria

1 messages · Page 1 of 1 (latest)

sage pike
#

I have an input type "foo" | "barX" | "batX" and would like to derive a type only contains the string literals ending with X but without X: "bar" | "bat".
I triedts Input extends `${infer A}X` ? A : neverbut as soon as Input contains a single "invalid" value it becomes never.
Playground below.

cobalt hawkBOT
#
Function#5603

Preview:ts ... type Foo = Input extends `${infer A}X` ? A : never ...

sage pike
#

lol i think i found the solution, please let me know if this is the right way or not:ts Input extends `${infer A}.${HTTPCode}` | infer B ? A : neveri literally just added | infer B

cobalt rampart
#

original example would work with generics

type Foo<T> = T extends `${infer A}X` ? A : never
#

that makes it behave distributively on an union

sage pike
cobalt rampart