其他分享
首页 > 其他分享> > [Typescript Challenges] 28. Medium - Replace

[Typescript Challenges] 28. Medium - Replace

作者:互联网

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!'

 

/* _____________ Your Code Here _____________ */

type Replace<S extends string, From extends string, To extends string> = S extends `${infer P1}${From}${infer P2}` 
  ? From extends '' 
    ? S
    : `${P1}${To}${P2}`
  : S
type x = Replace<'foobarbar', '', 'foo'>

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<Replace<'foobar', 'bar', 'foo'>, 'foofoo'>>,
  Expect<Equal<Replace<'foobarbar', 'bar', 'foo'>, 'foofoobar'>>,
  Expect<Equal<Replace<'foobarbar', '', 'foo'>, 'foobarbar'>>,
  Expect<Equal<Replace<'foobarbar', 'bar', ''>, 'foobar'>>,
  Expect<Equal<Replace<'foobarbar', 'bra', 'foo'>, 'foobarbar'>>,
  Expect<Equal<Replace<'', '', ''>, ''>>,
]

You can also check whether From is '' in the first place.

type Replace<S extends string, From extends string, To extends string> =
    From extends '' ? S : S extends `${infer A}${From}${infer B}` ? `${A}${To}${B}` : S;

 

标签:Typescript,_____________,28,Replace,Challenges,extends,Expect,type,infer
来源: https://www.cnblogs.com/Answer1215/p/16686464.html