问题 #
实现 Replace<S, From, To> 将字符串 S 中的第一个子字符串 From 替换为 To 。
例如
type replaced = Replace<'types are fun!', 'fun', 'awesome'> // 期望是 'types are awesome!'解答 #
type Replace<S extends string, FROM extends string, TO extends string> = FROM extends '' ? S : S extends `${infer T}${FROM}${infer U}` ? `${T}${TO}${U}`: S拆分 #
- 需要限制三个泛型都为字符串
- 如果
FORM为空就是没有需要替换 - 通过
infer保存前后字符,去除FORM - 使用
TO实现替换效果