Permutation
介绍
计算字符串的长度,类似于 String#length
起点
ts
/* _____________ Your Code Here _____________ */typeLengthOfString <S extends string> = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeLengthOfString <S extends string> = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
// 方法1// 这里思考以下, 为什么字符串的length属性返回类型是个number, 而不是和数组一样的数值字面量类型呢// 第二个是, T 为什么不能直接赋值位空数组. TypeScript 在处理泛型参数时,会先检查类型约束(extends),然后才考虑默认值。typeStrToArr <S extends string ,T extends any[]> =S extends ''? []:S extends `${inferF }${inferR }`? [...T ,F , ...StrToArr <R ,T >]:T ;typeLengthOfString <S extends string> =StrToArr <S , []>['length'];
ts
// 方法1// 这里思考以下, 为什么字符串的length属性返回类型是个number, 而不是和数组一样的数值字面量类型呢// 第二个是, T 为什么不能直接赋值位空数组. TypeScript 在处理泛型参数时,会先检查类型约束(extends),然后才考虑默认值。typeStrToArr <S extends string ,T extends any[]> =S extends ''? []:S extends `${inferF }${inferR }`? [...T ,F , ...StrToArr <R ,T >]:T ;typeLengthOfString <S extends string> =StrToArr <S , []>['length'];
ts
// most populartypeLengthOfString <S extends string,T extends string[] = []> =S extends `${inferF }${inferR }`?LengthOfString <R , [...T ,F ]>:T ['length'];
ts
// most populartypeLengthOfString <S extends string,T extends string[] = []> =S extends `${inferF }${inferR }`?LengthOfString <R , [...T ,F ]>:T ['length'];