TypeScript: type aliases to check type equality
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: Jest, TypeScript
This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post.
These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in a simple syntax.
({} as Expect>);
Here are the type aliases.
export type Expect= T; export type Equal = ( () => T extends A ? 1 : 2) extends < T >() => T extends B ? 1 : 2 ? true : false; export type NotEqual = Equal extends true ? false : true;
The expression export type Equal = (
The type alias Equal is used to compare two types A and B and determine if they are equal.
The comparison is performed using conditional type inference in TypeScript. The expression
Similarly,
The overall expression (
Therefore, the Equal type is true if types A and B are equal, and false otherwise.
Here is the unit test example asserting different types.
import { type Equal, type Expect } from './testHelpers'; describe('testHelpers', () => { describe('Equal, Expect type alias', () => { it('should assert never type', () => { type Value = never; type Expected = never; ({} as Expect>); }); it('should assert unknown type', () => { type Value = unknown; type Expected = unknown; ({} as Expect >); }); it('should assert literal types', () => { type Value = 'hello'; type Expected = 'hello'; ({} as Expect >); }); it('should assert union types', () => { type Value = string | number; type Expected = string | number; ({} as Expect >); }); it('should assert intersection types', () => { type Value = { a: number } & { b: string }; type Expected = { a: number } & { b: string }; ({} as Expect >); }); it('should assert tuple types', () => { type Value = [number, string]; type Expected = [number, string]; ({} as Expect >); }); it('should assert function types', () => { type Value = (x: number) => string; type Expected = (x: number) => string; ({} as Expect >); }); it('should assert array types', () => { type Value = number[]; type Expected = number[]; ({} as Expect >); }); it('should assert object types', () => { type Value = { a: number; b: string }; type Expected = { a: number; b: string }; ({} as Expect >); }); }); });