I have 2 types that should never intersect. Is there a way to make the typechecker flag when they do? Ideally, I'd like to do this purely in the types world without declaring any redundant variables.
Example:
type A = 1 | 2 // Must be different from B
type B_OK = 3
type B_FAIL = 2 | 3
// What I want (pseudo Typescript)
type AssertDifferent<X,Y> = Extract<X,Y> extends never ? any : fail // Fail if the types intersect
// Expected result (pseudo Typescript)
AssertDifferent<A,B_OK> // TS is happy
AssertDifferent<A,B_FAIL> // Fails type check
Your best bet is to make your conditional type return true or false, and then try to assign true to the result. Like so:
type A = 1 | 2 // Must be different from B
type B_OK = 3
type B_FAIL = 2 | 3
type AssertTrue<T extends true> = T;
type IsDifferent<X,Y> = Extract<X,Y> extends never ? true : false
type result1 = AssertTrue<IsDifferent<A, B_OK>>; // OK
type result2 = AssertTrue<IsDifferent<A, B_FAIL>>; // Error
You can use the new @ts-expect-error comments feature in version 3.9 on the second line to enforce that the error always throws.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With