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

30. LengthOfString #39

Open
astak16 opened this issue Jul 18, 2022 · 0 comments
Open

30. LengthOfString #39

astak16 opened this issue Jul 18, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jul 18, 2022

题目

题目链接:LengthOfString解答

实现 LengthOfString,获取字符串的长度:

import type { Equal, Expect } from "@type-challenges/utils";

type cases = [
  Expect<Equal<LengthOfString<"">, 0>>,
  Expect<Equal<LengthOfString<"kumiko">, 6>>,
  Expect<Equal<LengthOfString<"reina">, 5>>,
  Expect<Equal<LengthOfString<"Sound! Euphonium">, 16>>
];

答案

方法一

type StringToArray<T extends string> = T extends `${infer F}${infer Rest}`
  ? [F, ...StringToArray<Rest>]
  : [];
type LengthOfString<T extends string> = StringToArray<T>["length"];

知识点

  1. js 中计算字符串的长度,直接用 length 就可以获取字符串的长度
  2. 所以在 ts 类型中,"aa"["length"] 得到的结果是 number
  3. length 属性的还有元组类型
  4. 通过将字符串转换成元组,在取它的 length 属性,不就拿到元组的长度了么
  5. 元组的长度也就是字符串的长度

方法二

type LengthOfString<
  T extends string,
  R extends string[] = []
> = T extends `${infer F}${infer Rest}`
  ? LengthOfString<Rest, [F, ...R]>
  : R["length"];

方法三

type LengthOfString<T extends string, R extends string[] = []> = T extends ""
  ? R["length"]
  : T extends `${infer F}${infer Rest}`
  ? LengthOfString<Rest, [F, ...R]>
  : never;

知识点

方法二、方法三的思路和方法一是一样的,区别在于:

  • 方法二、方法三将字符串转换成的元组作为自己的第二个参数
  • 方法一是生成一个独立的元组
@astak16 astak16 added the medium label Jul 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant