aleclarson
aleclarson

Reputation: 19055

How to test if two types are exactly the same

Here is my first attempt: (playground link)

/** Trigger a compiler error when a value is _not_ an exact type. */
declare const exactType: <T, U extends T>(
    draft?: U,
    expected?: T
) => T extends U ? T : 1 & 0

declare let a: any[]
declare let b: [number][]

// $ExpectError
exactType(a, b)

Related: https://github.com/gcanti/typelevel-ts/issues/39

Upvotes: 51

Views: 38486

Answers (7)

jcalz
jcalz

Reputation: 330161

Ah, the type-level equality operator as requested in microsoft/TypeScript#27024. @MattMcCutchen has come up with a solution, described in a comment on that issue involving generic conditional types which does a decent job of detecting when two types are exactly equal, as opposed to just mutually assignable. In a perfectly sound type system, "mutually assignable" and "equal" would probably be the same thing, but TypeScript isn't perfectly sound. In particular, the any type is both assignable to and assignable from any other type, meaning that string extends any ? true : false and any extends string ? true: false both evaluate to true, despite the fact that string and any are not the same type.

Here's an IfEquals<T, U, Y, N> type which evaluates to Y if T and U are equal, and N otherwise.

type IfEquals<T, U, Y=unknown, N=never> =
  (<G>() => G extends T ? 1 : 2) extends
  (<G>() => G extends U ? 1 : 2) ? Y : N;

Let's see it work:

type EQ = IfEquals<any[], [number][], "same", "different">; // "different"

Okay, those are recognized as different types. There are probably some other edge cases where two types that you think are the same are seen as different, and vice versa:

type EQ1 = IfEquals<
  { a: string } & { b: number },
  { a: string, b: number },
  "same", "different">; // "different"!

type EQ2 = IfEquals<
  { (): string, (x: string): number },
  { (x: string): number, (): string },
  "same", "different">; // "different", as expected, but:

type EQ3 = IfEquals<
  { (): string } & { (x: string): number },
  { (x: string): number } & { (): string },
  "same", "different">; // "same"!! but they are not the same, 
// intersections of functions are order-dependent

Anyway, given this type we can make a function that generates an error unless the two types are equal in this way:

/** Trigger a compiler error when a value is _not_ an exact type. */
declare const exactType: <T, U>(
  draft: T & IfEquals<T, U>,
  expected: U & IfEquals<T, U>
) => IfEquals<T, U>

declare let a: any[]
declare let b: [number][]

// $ExpectError
exactType(a, b) // error

Each argument has a type T or U (for type inference of the generic parameter) intersected with IfEquals<T, U> so that there will be an error unless T and U are equal. This gives the behavior you want, I think.

Note that the arguments of this function are not optional. I don't really know why you wanted them to be optional, but (at least with --strictNullChecks turned on) it weakens the check to do so:

declare let c: string | undefined
declare let d: string
exactType(c, d) // no error if optional parameters!

It's up to you if that matters.

Upvotes: 74

Joseph Garrone
Joseph Garrone

Reputation: 1792

I wrote a library, tsafe, that lets you do that.

enter image description here

Thank @jcalz, your answer helped a lot in making this possible!

Upvotes: 10

DerBesondereEin
DerBesondereEin

Reputation: 470

If you are looking for a pure typescript solution without any third-party library dependency, this one should work for you

export function assert<T extends never>() {}
type TypeEqualityGuard<A,B> = Exclude<A,B> | Exclude<B,A>;

And usage like

assert<TypeEqualityGuard<{var1: string}, {var1:number}>>(); // returns an error
assert<TypeEqualityGuard<{var1: string}, {var1:string}>>(); // no error

Upvotes: 15

Almaju
Almaju

Reputation: 1383

I was a bit annoyed that the other propositions imply that I only get false without any detail to understand why it is failing.

This is how I solved it for my use case (and it gives readable errors):

type X = { color: string };
type Y = { color: string };
type Z = { color: number };

const assert = <A, B extends A, C extends B>() => {}

/** Pass! */
assert<X, Y, X>(); 

/**
 * Fail nicely:
 * Type 'Z' does not satisfy the constraint 'X'.
 * Types of property 'color' are incompatible.
 * Type 'number' is not assignable to type 'string'.
 */
assert<X, Z, X>(); 

Upvotes: 7

Ronald C
Ronald C

Reputation: 367

The most robust Equals that I've seen so far (though still not perfect) is this one:

type Equals<A, B> = _HalfEquals<A, B> extends true ? _HalfEquals<B, A> : false;

type _HalfEquals<A, B> = (
    A extends unknown
        ? (
              B extends unknown
                  ? A extends B
                      ? B extends A
                          ? keyof A extends keyof B
                              ? keyof B extends keyof A
                                  ? A extends object
                                      ? _DeepHalfEquals<A, B, keyof A> extends true
                                          ? 1
                                          : never
                                      : 1
                                  : never
                              : never
                          : never
                      : never
                  : unknown
          ) extends never
            ? 0
            : never
        : unknown
) extends never
    ? true
    : false;

type _DeepHalfEquals<A, B extends A, K extends keyof A> = (
    K extends unknown ? (Equals<A[K], B[K]> extends true ? never : 0) : unknown
) extends never
    ? true
    : false;

It fails for Equals<[any, number], [number, any]>, for example.

found here: https://github.com/Microsoft/TypeScript/issues/27024#issuecomment-845655557

Upvotes: 2

aleclarson
aleclarson

Reputation: 19055

edit: The most refined version can be found here

Here's the most robust solution I've found thus far:

// prettier-ignore
type Exact<A, B> = (<T>() => T extends A ? 1 : 0) extends (<T>() => T extends B ? 1 : 0)
    ? (A extends B ? (B extends A ? unknown : never) : never)
    : never

/** Fails when `actual` and `expected` have different types. */
declare const exactType: <Actual, Expected>(
    actual: Actual & Exact<Actual, Expected>,
    expected: Expected & Exact<Actual, Expected>
) => Expected

Thanks to @jcalz for pointing in the right direction!

Upvotes: 11

Luis H. Moreno
Luis H. Moreno

Reputation: 91

We should take different approaches depending on the problem. For example, if we know that we're comparing numbers with any, we can use typeof().

If we're comparing interfaces, for example, we can use this approach:

function instanceOfA(object: any): object is A {
    return 'member' in object;
}

Upvotes: -5

Related Questions