zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] 34. Medium - String to Union

typescript string to 34 union Medium
2023-09-14 08:59:12 时间

Implement the String to Union type. Type take string argument. The output should be a union of input letters

For example

type Test = '123';
type Result = StringToUnion<Test>; // expected to be "1" | "2" | "3"
/* _____________ Your Code Here _____________ */

type StringToUnion<T extends string> = T extends '' ? never : T extends `${infer First}${infer REST}` ? `${First}` | StringToUnion<REST>: never;


/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<StringToUnion<''>, never>>,
  Expect<Equal<StringToUnion<'t'>, 't'>>,
  Expect<Equal<StringToUnion<'hello'>, 'h' | 'e' | 'l' | 'l' | 'o'>>,
  Expect<Equal<StringToUnion<'coronavirus'>, 'c' | 'o' | 'r' | 'o' | 'n' | 'a' | 'v' | 'i' | 'r' | 'u' | 's'>>,
]