【发布时间】:2021-12-18 11:12:53
【问题描述】:
TLDR:
类似:
type type4= 5-1 //type 4
// also ok
type type4= '5'-'1' // type '4'
我怎样才能达到类似的效果?
详情
我想构建一个通用函数类型,它接收数字文字(或字符串文字)并返回数字的联合,直到'0'。例如,如果'3' 被传递,那么返回将是'0'|'1'|'2'。让我们称之为通用RangeUnion。
type Union01 = RangeUnion<'1'> // should be '0'|'1' - RangeUnion should be implemented
为什么?
这仅供参考,无需理解即可回答我的具体问题。如果您对上述问题没有答案,也许您可以为不同的实现提供一些想法。
我正在为反应组件构建开发人员 API,并且我想使用 typescript 创建复杂的类型推断。无需过多介绍:当数组中的每个项目都依赖于数组中的先前项目时,我有类型数组。我想创建类型的交集,直到数组中的给定类型,例如:
// utilities
type GetIndex<A extends any[], T> = {
[K in keyof A]: A[K] extends T ? K : never;
}[number];
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
// actual
type Arr = [{ type0: any }, { type1: any }, { type2: any },]
type Type1 = GetIndex<Arr, { type1: any }> // type is '1' - good
type Union01 = RangeUnion<Type1> // should be 0|1 - RangeUnion should be implemented
type DesiredType = UnionToIntersection<Arr[Union01]> //type is { type0: any } & { type1: any }
【问题讨论】:
-
谢谢!这对我来说应该足够了,你也可以链接这篇文章作为答案如果你喜欢并会接受它
-
看这个例子tsplay.dev/mbdx9w
-
是的,这直接回答了我的问题
标签: typescript