Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

「重学TS 2.0 」TS 练习题第四十八题 #69

Open
semlinker opened this issue Oct 12, 2021 · 4 comments
Open

「重学TS 2.0 」TS 练习题第四十八题 #69

semlinker opened this issue Oct 12, 2021 · 4 comments

Comments

@semlinker
Copy link
Owner

实现 ConsistsOnlyOf 工具类型,用于判断 LongString 字符串类型是否由 0 个或多个 Substring 字符串类型组成。具体的使用示例如下所示:

type ConsistsOnlyOf<LongString extends string, Substring extends string> = // 你的实现代码

type C0 = ConsistsOnlyOf<'aaa', 'a'> //=> true
type C1 = ConsistsOnlyOf<'ababab', 'ab'> //=> true
type C2 = ConsistsOnlyOf<'aBa', 'a'> //=> false
type C3 = ConsistsOnlyOf<'', 'a'> //=> true

请在下面评论你的答案

@zhaoxiongfei
Copy link

type ConsistsOnlyOf<LongString extends string, Substring extends string> = LongString extends ''
  ? true
  : LongString extends `${Substring}${infer B}`
    ? ConsistsOnlyOf<B, Substring>
    : false;

思路: 字符串匹配,利用 extends 、利用ts下支持的模板字符串语法,利用 infer 从开头一步步的去匹配,减治的思想。
随着递归的深入字符串愈来愈短,直至为空,注意空的话算匹配成功。

@zjxxxxxxxxx
Copy link

type ConsistsOnlyOf<
  LongString extends string,
  Substring extends string
> = LongString extends `${Substring}${infer R}`
  ? ConsistsOnlyOf<R, Substring>
  : LongString extends ""
  ? true
  : false;

@bill-lai
Copy link

type ConsistsOnlyOf<LongString extends string, Substring extends string> = 
  LongString extends '' 
    ? true
    : LongString extends `${Substring}${infer S}` 
      ? ConsistsOnlyOf<S, Substring>
      : false

@zhengyimeng
Copy link

type ConsistsOnlyOf<LongString extends string, Substring extends string> 
  = LongString extends `${Substring}${infer Others}`
    ? ConsistsOnlyOf<Others, Substring>
    : LongString extends '' ? true : false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants