How to use extends and keyof In Typescript
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.
Javascript
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
How to Test if Two Types are Exactly the Same in TypeScript ?
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
- Using Extract and keyof
- Using Mapped Types