How to check TypeScript type equality

Riley Tomasek

It can be useful to know if two TypeScript types are equal when working with generics or when you want to verify that first party types are aligned with types generated by a third party library.

This is a simple trick from Matt Pococks Zod tutorial.

type Expect<T extends true> = T;
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <
  T,
>() => T extends Y ? 1 : 2
  ? true
  : false;

Example usage:

// OK
type Person = { name: string };
const person = { name: 'bill' };
type verify = Expect<Equal<typeof person, Person>>

// OK
type Person2 = { name: string };
type verify2 = [
  Expect<Equal<typeof person, Person>>,
  Expect<Equal<Person2, Person>>
];

// TS ERROR
type NotPerson = { name: number };
type verify3 = Expect<Equal<NotPerson, Person>>