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'];