【发布时间】:2019-08-10 15:49:41
【问题描述】:
我声明枚举及其转换器:
enum E { A, B };
type TRANSFORM<T extends E> = T extends E.A ? E.B : E.A;
并声明具有两个元素的数组类型,其中第二个是第一个元素的转换类型:
type qwe<T extends E> = [T, TRANSFORM<T>];
当我提供特殊的枚举元素时,它工作正常:
const element: qwe<E.A> = [E.A, E.A]; // Ok: Error: (Type 'E.A' is not assignable to type 'E.B')
如何声明这些元素的数组?我找到的唯一方法是:
const arr: (qwe<E.A> | qwe<E.B>)[] = [[E.A, E.A], [E.B, E.A]];
// Ok: Error: (Type '[E.A, E.A]' is not assignable to type '[E.A, E.B] | [E.B, E.A]')
但输入为
type b = qwe<E.A> | qwe<E.B>;
可能太大,当枚举E 将包含更多元素。简而言之,我该怎么写?
我试图这样声明:
type b = qwe<E>;
但它没有按预期工作。例如这个数组是正确的:
const arr: qwe<E>[] = [[E.A, E.A], [E.B, E.A]];
【问题讨论】:
-
它不是分布式的。您需要将其声明为
arr: qwe<E.A | E.B> = [[E.A, E.B], [E.B, E.A]] -
@AluanHaddad,当我使用
qwe<E.A | E.B>[]时,在此数组中未找到错误:[[E.A, E.A], [E.B, E.A]]。它等于qwe<E>[]。
标签: typescript typescript-typings