【发布时间】:2020-11-16 19:51:53
【问题描述】:
在 TypeScript 4.1 中,哪个开发版本已经可以通过 npm 获得,支持 Recursive Conditional Types 和 Template literal types 这创造了一些非常有趣的机会
假设我们有以下类型
// type is '0123456';
const actualString = '0123456';
任务
将字符串按字符拆分为新数组,但应保留数组元素的类型
// Unfortunately, type is string[]
const chars1 = actualString.split('');
// Throws error: string[] is not assignable ['0', '1', '2', '3', '4', '5', '6']
const chars2: ['0', '1', '2', '3', '4', '5', '6'] = actualString.split('');
我对这个的看法
type StringToChars<BASE extends string> = BASE extends `${infer _}`
? BASE extends `${infer FIRST_CHAR}${infer REST}` // BASE is inferable
? [FIRST_CHAR, ...StringToChars<REST>] // BASE has at least one character
: [] // BASE is empty string
: string[]; // BASE is simple string
// type is ['0', '1', '2', '3', '4', '5', '6']
type Chars = StringToChars<'0123456'>;
问题
此解决方案适用于少于 14 个字符的字符串。
// Throws: Type instantiation is excessively deep and possibly infinite. (ts2589)
type LargeCharsArray = StringToChars<'0123456789 01234'>
显然它遇到了打字稿类型递归限制,在检查第 14 个字符后,它给我们留下了[<first 14 characters>, ...any[]]。
问题
这个递归类型调用看起来很糟糕,所以我想知道,有没有更可靠的方法将字符串类型转换为字符类型的数组?
【问题讨论】:
标签: typescript types beta