这非常简单,这里是the link to playground
正如我所注意到的,当您从If<>
中的条件中删除元组类型时,一切都会按预期进行。但是我不想这样做(t2
断言打击),而且我想了解这种情况。这只是一个错误吗?为什么And<>
类型总是扩展为true
?
type If<
TCond extends boolean,
TIfTrue,
TElse
> = [TCond] extends [true] ? TIfTrue : TElse; // if you remove tuples, it works
type Not<T extends boolean> = If<(T), false, true>;
type IsNever<TSuspect> = TSuspect extends never ? true : false;
type AssertFalse<TSuspect extends false> = TSuspect;
type AssertTrue <TSuspect extends true> = TSuspect;
// V~~ always true
type And<T extends boolean[]> = Not<Not<IsNever<Extract<T[number], false>>>>;
type AndExpected<T extends boolean[]> = IsNever<Extract<T[number], false>>;
type t0 = AssertFalse<Not<true>>;
type t1 = AssertTrue<Not<false>>;
type t2 = AssertTrue<Not<boolean>>;
type t3 = AssertFalse<And<[false]>>; // ????
type t4 = AssertFalse<AndExpected<[false]>>;
答案 0 :(得分:1)
首先,我将尝试解释为什么带元组的If与不带元组的If不同:
type If<
TCond extends boolean,
TIfTrue,
TElse
> = [TCond] extends [true] ? TIfTrue : TElse; // if you remove tuples, it works
type If2<
TCond extends boolean,
TIfTrue,
TElse
> = TCond extends true ? TIfTrue : TElse;
type Not<T extends boolean> = If<(T), false, true>;
type Not2<T extends boolean> = If2<(T), false, true>;
// with tuples, Not<boolean> is true because that's how you set it up
type A1 = Not<boolean>; // true
type A2 = Not<true>; // false
type A3 = Not<false>; // true
// without typles, TCond extends true is distributive over union types,
// and boolean is really just a union of true | false,
// so Not2<boolean> is boolean
type B1 = Not2<boolean>; // boolean
type B2 = Not2<true>; // false
type B3 = Not2<false>; // true
好的,现在问问题。这是我(和Titian Cernicova-Dragomir)发现的奇怪东西:
type SameAsT<T extends boolean> = Not<Not<T>>;
type X1 = SameAsT<false>; // true !
type X2 = SameAsT<true>; // true again
// but why?
如果展开所有文字类型,它将按预期工作:
type ReallyNotFalse = [false] extends [true] ? false : true; // true
type ReallyNotNotFalse = [([false] extends [true] ? false : true)] extends [true] ? false : true; // false
看起来像编译器中的错误。
偶然地,基于Not
且没有元组的If
可以正常工作
type SameAsT2<T extends boolean> = Not2<Not2<T>>;
type Y1 = SameAsT2<false>; // false
type Y2 = SameAsT2<true>; // true
因此,可以使用其他方法来抑制条件中的分布式联合类型并使所讨论的代码正常工作。一种方法是添加多余的条件,该条件始终评估为true,并且没有TCond
作为要检查的类型:
type If<
TCond extends boolean,
TIfTrue,
TElse
> = {} extends TCond ? TCond extends true ? TIfTrue : TElse : never;
type Not<T extends boolean> = If<(T), false, true>;
type IsNever<TSuspect> = TSuspect extends never ? true : false;
type AssertFalse<TSuspect extends false> = TSuspect;
type AssertTrue <TSuspect extends true> = TSuspect;
// V~~ always true
type And<T extends boolean[]> = Not<Not<IsNever<Extract<T[number], false>>>>;
type AndExpected<T extends boolean[]> = IsNever<Extract<T[number], false>>;
type t0 = AssertFalse<Not<true>>;
type t1 = AssertTrue<Not<false>>;
type t2 = AssertTrue<Not<boolean>>;
type t3 = AssertFalse<And<[false]>>;
type t4 = AssertFalse<AndExpected<[false]>>;