Check if Value with Unknown Type contains Property in TS

avatar

Borislav Hadzhiev

Last updated: Mar 11, 2022

banner

Check out my new book

Check if Value with Unknown Type contains Property in TS #

Use a user-defined type guard to check if a value with unknown type contains a property in TypeScript. The user-defined type guard consists of a function that checks if the specific property is contained in the object and returns a predicate.

index.ts
interface Person { name: string; age: string; } function isPerson(obj: unknown): obj is Person { return ( typeof obj === 'object' && obj !== null && 'name' in obj && 'age' in obj ); } const obj: unknown = { name: 'James', age: 30, }; if (isPerson(obj)) { console.log(obj.name); // 👉️ "James" console.log(obj.age); // 👉️ 30 }

We used a user-defined type guard to check if an object contains the name and age properties.

The obj is Person syntax is a type predicate where obj must be the name of the parameter the function takes.

The first thing we did in the function is check if the passed in value has a type of object.

Unfortunately, we also have to check that the object is not equal to null, because null has a type of object in JavaScript (and TypeScript).

index.ts
console.log(typeof null); // 👉️ "object"

At this point, we can use the in operator to check if the name and age properties are contained in the object.

index.ts
const obj2 = { name: 'Tom', age: 29, }; console.log('name' in obj2); // 👉️ true console.log('age' in obj2); // 👉️ true console.log('test' in obj2); // 👉️ false

The in operator checks if a specific property is contained in the object or its prototype chain and returns a boolean result - true if it is and false otherwise.

User-defined type guards are useful in this situation, because in the if block TypeScript types the object to be of the specified type.

index.ts
interface Person { name: string; age: string; } function isPerson(obj: unknown): obj is Person { return ( typeof obj === 'object' && obj !== null && 'name' in obj && 'age' in obj ); } const obj: unknown = { name: 'James', age: 30, }; if (isPerson(obj)) { // 👉️ obj is of type Person here console.log(obj.name); // 👉️ "James" console.log(obj.age); // 👉️ 30 }

Once we are in the if block, TypeScript knows the obj has a type of Person and allows us to access all of the properties a Person has.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.