Open yunliuyan opened 1 year ago
基于replace进行递归
type ReplaceAll<S extends string, From extends string, To extends string> = S extends '' ? '' : S extends `${infer L}${From}${infer R}` ? `${L}${ReplaceAll<`${To}${R}`, From, To>}` : S;
type replaced = ReplaceAll<'t y p e s', ' ', ''>; // 'types'
type ReplaceAll<S extends string, From extends string, To extends string>
= From extends '' ? S : S extends `${infer X1}${From}${infer X2}` ?
`${X1}${To}${ReplaceAll<X2, From, To>}` : S;
type replaceAll = ReplaceAll<'t y p e s', ' ', ''> // 期望是 'types'
type ReplaceAll<S extends string, From extends string, To extends string> =
From extends '' ? S : S extends `${infer U}${From}${infer R}`? `${U}${To}${ReplaceAll<R, From, To>}` : S;
type replaced = ReplaceAll<'t y p e s', ' ', ''>
type MyReplaceAll<S extends string, From extends string, To extends string> = S extends '' ? '' : S extends `${infer L}${From}${infer R}` ? `${L}${To}${MyReplaceAll<`${R}`, From, To>}` : S;
type replacedTest = MyReplaceAll<'t y p e s', ' ', ''>; // 'types'
ReplaceAll
实现
ReplaceAll<S, From, To>
将一个字符串S
中的所有子字符串From
替换为To
。例如