yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00016-medium-replace #16

Open yunliuyan opened 11 months ago

yunliuyan commented 11 months ago

Replace 中等 #template-literal

by Anthony Fu @antfu

接受挑战    English 日本語 한국어

实现 Replace<S, From, To> 将字符串 S 中的第一个子字符串 From 替换为 To

例如

type replaced = Replace<'types are fun!', 'fun', 'awesome'> // 期望是 'types are awesome!'

返回首页 分享你的解答 查看解答
yunliuyan commented 11 months ago

思路

infer 大法好

代码实现

type Replace<S extends string, From extends string, To extends string> = S extends `${infer L}${From}${infer R}` ? `${L}${To}${R}` : never;

type replaced = Replace<'types are fun!', 'fun', 'awesome'> // 期望是 'types are awesome!'
liangchengv commented 11 months ago
type Replace<S extends string, From extends string, To extends string> = S extends `${infer U}${From}${infer R}` ? `${U}${To}${R}` : S;

type replaced = Replace<'types are fun!', 'fun', 'awesome'>; 
Janice-Fan commented 11 months ago
type Replace<T extends string, U extends string, P extends string> = T extends `${infer t}${U}${infer r}` ? `${t}${P}${r}` : never;

type replaced = Replace<'types are fun!', 'fun', 'awesome'> // 期望是 'types are awesome!'
wudu8 commented 11 months ago
type MyReplace<S extends string, From extends string, To extends string> = S extends `${infer L}${From}${infer R}` ? `${L}${To}${R}` : never;

type replaced = MyReplace<'types are fun!', 'fun', 'awesome'> // 期望是 'types are awesome!'