This article will show how we can test if the two types are the same in TypeScript. Types in Typescript are used to define and describe the data in our code. Some of the types are number, string, boolean, etc.
Below are the possible approaches:
Table of Content
Using extends and keyof
In this approach, we are using extends and keyof to check if the keys of type T extend the key of type U and also if the key of type U extends the key of type T. When both of the conditions are true then we can display true as a result which indicated that both types are the exactly same set of keys.
Syntax:
type TypeEquality<T, U> = keyof T extends keyof U ? (keyof U extends keyof T ? true : false) : false;
Example: Below is the implementation of the above-discussed approach.
type approach1<T, U> = keyof T extends keyof U ? (keyof U extends keyof T ? true : false ) : false ;
type Type1 = { a: number; b: string }; type Type2 = { a: number; b: string }; const res1: approach1<Type1, Type2> = true ;
// Types are same console.log(res1); const res2: approach1<Type1, { a: number;
b: string; c: boolean
}> = false ; // Types are different
console.log(res2); |
Output:
true
false
Using Extract and keyof
In this approach, we are using the Extract and keyof to check if there are no common keys between the two types of T and U. If there are no common keys then it is true and we are printing true results which are the same types.
Syntax:
type TypeEquality<T, U> = Extract<keyof T, keyof U> extends never ? false : true;
Example: Below is the implementation of the above-discussed approach.
type approach2<T, U> = Extract<keyof T, keyof U> extends never ? Extract<keyof U, keyof T> extends never
? true
: false
: false ;
type Type1 = { a: number; b: string }; type Type2 = { a: number; b: string }; const res1: approach2<Type1, Type2> = true as approach2<Type1, Type2>;
// Types are the same console.log(res1); const res2: approach2<Type1, { a: number;
b: string; c: boolean
}> = false as approach2<Type1,
{ a: number; b: string; c: boolean }>;
// Types are different console.log(res2); |
Output:
true
false
Using Mapped Types
In this approach, we are using Mapped Types in which we are checking if each key in type T is the same key in type U. If the condition is true, then the two types are the same. Using this approach, we can make sure that there is proper one-to-one mapping of keys within the two types.
Syntax:
type TypeEquality<T, U> = { [K in keyof T]: K extends keyof U ? T[K] : never } extends T ? true : false;
Example: Below is the implementation of the above-discussed approach.
type approach3<T, U> = keyof T extends keyof U ? keyof U extends keyof T
? true
: false
: false ;
type Type1 = { a: number; b: string }; type Type2 = { a: number; b: string }; const res1: approach3<Type1, Type2> = true ;
// Types are same console.log(res1); const res2: approach3<Type1, { a: number;
b: string; c: boolean
}> = false ;
// Types are different console.log(res2); |
Output:
true
false