Typescript类型体操 - Replace

题目

中文

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

例如

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

English

Implement Replace<S, From, To> which replace the string From with To once in the given string S

For example

type replaced = Replace<'types are fun!', 'fun', 'awesome'> // expected to be 'types are awesome!'

答案

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

在线演示

posted @ 2022-09-05 20:01  Laggage  阅读(128)  评论(0编辑  收藏  举报