TypeScript: How to Check if a Property Exists in an Object

Updated: January 8, 2024 By: Guest Contributor Post a comment

Introduction

Scarcely a day passes that the gallant coder of TypeScript does not journey through the wild terrain of objects and their properties. Perchance you may wonder how to discern if a property, like a hawk on the wing, does indeed belong to the object or if it is but a phantom. Herein we shall arm you with knowledge, as a knight with his lance, to verify the existence of such properties.

Using the ‘in’ Operator

Our first weapon in this quest is the venerable ‘in’ operator. As if shouting a challenge into the vast forests of code, it returns a simple true or false, telling whether a property exists.

interface Parchment {
  script?: string;
}

const letter: Parchment = { script: 'Yours Truly' };

if ('script' in letter) {
  console.log('The script property exists!');
} else {
  console.log('There is no script to be found here.');
}

Optional Chaining and the ‘undefined’

Behold, the optional chaining, a language feature akin to sending a scout ahead. It allows for properties to be queried without the fearsome crash – a courteous guardian against the undefined.

let manuscript: Parchment = {};

if (manuscript?.script !== undefined) {
  console.log('The script is penned herein.');
} else {
  console.log('The parchment is blank, the script is absent.');
}

Type Guards by the ‘typeof’ Incantation

Sometimes the situation demands a rigorous check, a type guard. The ‘typeof’ acts as such, enabling the TypeScript knight to declare certainties about the type of variables before proceeding.

let missive: any = { message: 'Keep steadfast!' };

if (typeof missive.script !== 'undefined') {
  console.log('The missive carries a script.');
} else {
  console.log('The script is missing from this missive.');
}

Reflection by ‘Reflect.has’

Deep in the chambers of ECMAScript, there lies the Reflect object, holding powers such as ‘Reflect.has’, which informs whether an object has a property.

const declaration: object = { clause: true };

if (Reflect.has(declaration, 'clause')) {
  console.log('The declaration contains a clause.');
} else {
  console.log('The declaration is bereft of any clause.');
}

HasKey Function: A Custom-Made Tool

Winding down our path, we may craft a function fitting the hand as a custom-made gauntlet, providing an elegant way to test for property existence.

function hasKey(obj: T, key: keyof any): key is keyof T {
  return key in obj;
}

const edict = { decree: true };

if (hasKey(edict, 'decree')) {
  console.log('The edict possesses a decree.');
} else {
  console.log('The decree is absent from the edict.');
}

Generics and keyof

In the pursuit of a more precise and flexible brilliance, the TypeScript wizard might deploy generics along with ‘keyof’ to peer into the soul of objects.

function propertyExists<K extends string, T extends Record<K, any>>(obj: T, key: K): boolean {
  return key in obj;
}

const tome = { spell: 'Expecto Patronum' };

if (propertyExists(tome, 'spell')) {
  console.log('A spell is etched within this tome.');
} else {
  console.log('The tome holds no words of power.');
}

Conclusion

Thereupon we close our chronicle, equipped and enlightened in the manifold ways to verify the possession of properties within objects in TypeScript. Each method an arrow in your quiver, preparing you for the eventualities that emerge as you pen your code in this grand tapestry of TypeScript saga.