Skip to main content
TypeScript

Same Type Assertion

You can check whether two types are the same by using the following type helper.

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

The Equals<X, Y> type helper resolves to true when X and Y are the same type. Otherwise, it resolves to false.

Here is the original code for Equals: https://github.com/Microsoft/TypeScript/issues/27024#issuecomment-421529650.

To go one step further, you can create a noop function that forces a type error when X and Y are not the same type like this:

typescript
const assertSameType = <T extends true>() => {
  // noop
};

assertSameType<Equals<X, Y>>();