Home > Back-end >  Matching chars in a string type
Matching chars in a string type

Time:11-30

Hope you are well. I have a question. I'm looking to make a type that loops through a string one char at a time and if all of the chars match the lookup chars then it should return the string and if not it should return never or a empty string. Been having some trouble with this because what i have basically behaves like Trim and that is not really what i am looking for. As i am looking for more of a pattern matching type. Hoping you can provide some help with this and thanks in advance!

type Char =
  | "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7"
  | "8" | "9" | "a" | "A" | "b" | "B" | "c" | "C"
  | "d" | "D" | "e" | "E" | "f" | "F";

type Word<S extends string> = S extends `${Char}${infer Rest}` ? Word<Rest> : never;

Code: TS Playground

CodePudding user response:

Store the original string and return it if the string is empty:

type Word<S extends string, Original = S> = S extends `${infer _ extends Char}${infer Rest}`
  ? Word<Rest, Original> : S extends "" ? Original : never;

Playground

  • Related