跳到主要内容

String to Union

介绍

实现一个将接收到的String参数转换为一个字母Union的类型。

ts
type Test = '123';
type Result = StringToUnion<Test>; // expected to be "1" | "2" | "3"
ts
type Test = '123';
type Result = StringToUnion<Test>; // expected to be "1" | "2" | "3"
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type StringToUnion<T extends string> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<StringToUnion<''>, never>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<StringToUnion<'t'>, 't'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<StringToUnion<'hello'>, 'h' | 'e' | 'l' | 'l' | 'o'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<StringToUnion<'coronavirus'>, 'c' | 'o' | 'r' | 'o' | 'n' | 'a' | 'v' | 'i' | 'r' | 'u' | 's'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type StringToUnion<T extends string> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<StringToUnion<''>, never>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<StringToUnion<'t'>, 't'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<StringToUnion<'hello'>, 'h' | 'e' | 'l' | 'l' | 'o'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<StringToUnion<'coronavirus'>, 'c' | 'o' | 'r' | 'o' | 'n' | 'a' | 'v' | 'i' | 'r' | 'u' | 's'>>,
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
type StringToUnion<T extends string> = T extends `${infer F}${infer Rest}`
? F | StringToUnion<Rest>
: never
 
ts
type StringToUnion<T extends string> = T extends `${infer F}${infer Rest}`
? F | StringToUnion<Rest>
: never
 
view more solutions