zhengyimeng/awesome-typescript

实现 ReplaceAll,用于实现字符串类型的替换操作

Opened this issue · 0 comments

type ReplaceAll<
  S extends string,
  From extends string,
  To extends string
> = S extends `${infer A}${From}${infer Rest}`
  ? `${A}${To}${ReplaceAll<Rest, From, To>}`
  : S;

type C0 = ReplaceAll<"", "", "">; // ''
type C1 = ReplaceAll<"foobar", "bar", "foo">; // "foofoo"
type C2 = ReplaceAll<"foobarbar", "bar", "foo">; // "foofoobar"
type C3 = ReplaceAll<"foobarfoobar", "ob", "b">; // "fobarfobar"