跳到主要内容

Permutation

介绍

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

View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type LengthOfString<S extends string> = any
 
/* _____________ Test Cases _____________ */
 
 
 
type cases = [
Expect<Equal<LengthOfString<''>, 0>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<LengthOfString<'kumiko'>, 6>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<LengthOfString<'reina'>, 5>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<LengthOfString<'Sound! Euphonium'>, 16>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type LengthOfString<S extends string> = any
 
/* _____________ Test Cases _____________ */
 
 
 
type cases = [
Expect<Equal<LengthOfString<''>, 0>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<LengthOfString<'kumiko'>, 6>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<LengthOfString<'reina'>, 5>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<LengthOfString<'Sound! Euphonium'>, 16>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// 方法1
// 这里思考以下, 为什么字符串的length属性返回类型是个number, 而不是和数组一样的数值字面量类型呢
// 第二个是, T 为什么不能直接赋值位空数组. TypeScript 在处理泛型参数时,会先检查类型约束(extends),然后才考虑默认值。
type StrToArr<S extends string , T extends any[]> = S extends ''
? []
: S extends `${infer F}${infer R}`
? [...T, F, ...StrToArr<R, T>]
: T;
type LengthOfString<S extends string> = StrToArr<S, []>['length'];
 
ts
// 方法1
// 这里思考以下, 为什么字符串的length属性返回类型是个number, 而不是和数组一样的数值字面量类型呢
// 第二个是, T 为什么不能直接赋值位空数组. TypeScript 在处理泛型参数时,会先检查类型约束(extends),然后才考虑默认值。
type StrToArr<S extends string , T extends any[]> = S extends ''
? []
: S extends `${infer F}${infer R}`
? [...T, F, ...StrToArr<R, T>]
: T;
type LengthOfString<S extends string> = StrToArr<S, []>['length'];
 
ts
// most popular
 
type LengthOfString<
S extends string,
T extends string[] = []
> = S extends `${infer F}${infer R}`
? LengthOfString<R, [...T, F]>
: T['length'];
 
 
ts
// most popular
 
type LengthOfString<
S extends string,
T extends string[] = []
> = S extends `${infer F}${infer R}`
? LengthOfString<R, [...T, F]>
: T['length'];
 
 
view more solutions