type-challenges:String to Union

27 阅读1分钟

String to Union

问题描述

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

例如

type Test = '123';
type Result = StringToUnion<Test>; // expected to be "1" | "2" | "3"
// ============= Test Cases =============
import type { Equal, Expect } from './test-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'>>,
]
​
​
// ============= Your Code Here =============type StringToUnion<T extends string> = T extends `${infer F}${infer R}`?F|StringToUnion<R>:never

我发现遇到字符串类型的题,基本都需要使用模板字符串将字符串拆开,有思路这道题就很简单,一个个拆开后使用运算符 | 将第一个字符和剩余字符串联合起来即可。