Skip to content

字符串转联合类型

约 279 字小于 1 分钟

2022-12-01

题目

Github: StringToUnion

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

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

解题思路

通过模板字面量类型 和 条件类型推断,从字符串中取出一个个字符,并使用 尾递归的方式,将字符串转为联合类型。

答案

type StringToUnion<S extends string> = 
  S extends `${infer L}${infer R}` ? `${L | StringToUnion<R>}` : never

验证

import { Equal, Expect } from '~/tc-utils'
type StringToUnion<S extends string> = 
  S extends `${infer L}${infer R}` ? `${L | StringToUnion<R>}` : never

// ---cut---
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'>>,
]

参考