Typescript类型体操 - Length of String

题目

中文

计算字符串的长度,类似于 String#length

English

Compute the length of a string literal, which behaves like String#length.

答案

解法1

type StringToArrray<T extends string> = T extends `${infer L}${infer R}` ? [L, ...StringToArrray<R>] : [];
type LengthOfString<S extends string> = StringToArrray<S>['length'];

在线演示

解法2

type LengthOfString<S extends string, U extends any[] = []> = S extends `${infer L}${infer R}` ? LengthOfString<R, [L, ...U]> : U['length'];

在线演示

posted @ 2022-09-06 20:36  Laggage  阅读(117)  评论(0编辑  收藏  举报