String to Union
介绍
实现一个将接收到的String参数转换为一个字母Union的类型。
ts
type Test = '123';type Result = StringToUnion<Test>; // expected to be "1" | "2" | "3"
View on GitHubts
type Test = '123';type Result = StringToUnion<Test>; // expected to be "1" | "2" | "3"
起点
ts
/* _____________ Your Code Here _____________ */typeStringToUnion <T extends string> = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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'>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeStringToUnion <T extends string> = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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'>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
typeStringToUnion <T extends string> =T extends `${inferF }${inferRest }`?F |StringToUnion <Rest >: never
ts
typeStringToUnion <T extends string> =T extends `${inferF }${inferRest }`?F |StringToUnion <Rest >: never