跳到主要内容

CheckRepeatedchars

介绍

判断一个string类型中是否有相同的字符

ts
type CheckRepeatedChars<T extends string> = any
ts
type CheckRepeatedChars<T extends string> = any
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type CheckRepeatedChars<T extends string> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<CheckRepeatedChars<'abc'>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<CheckRepeatedChars<'abb'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<CheckRepeatedChars<'cbc'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<CheckRepeatedChars<''>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type CheckRepeatedChars<T extends string> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<CheckRepeatedChars<'abc'>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<CheckRepeatedChars<'abb'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<CheckRepeatedChars<'cbc'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<CheckRepeatedChars<''>, false>>,
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
// most popular
 
type CheckRepeatedChars<T extends string> = T extends `${infer F}${infer E}`
? E extends `${string}${F}${string}`
? true
: CheckRepeatedChars<E>
: false
 
ts
// most popular
 
type CheckRepeatedChars<T extends string> = T extends `${infer F}${infer E}`
? E extends `${string}${F}${string}`
? true
: CheckRepeatedChars<E>
: false
 
ts
// my
type strToUnion<T extends string> = T extends `${infer F}${infer R}` ? F | strToUnion<R> : never
 
 
type CheckRepeatedChars<T extends string> = T extends `${infer F}${infer R}` ? F extends strToUnion<R> ? true : CheckRepeatedChars<R> : false
 
ts
// my
type strToUnion<T extends string> = T extends `${infer F}${infer R}` ? F | strToUnion<R> : never
 
 
type CheckRepeatedChars<T extends string> = T extends `${infer F}${infer R}` ? F extends strToUnion<R> ? true : CheckRepeatedChars<R> : false
 
view more solutions