Property check

2 snippets across 2 stacks — JavaScript, TypeScript

JSJavaScript

Checking Property Existence

JS · Objects
syntax
Object.hasOwn(obj, prop)
"prop" in obj
example
const user = { name: "Lina", age: 28 };

console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "email")); // false
console.log("toString" in user);           // true (inherited)
console.log(Object.hasOwn(user, "toString")); // false

Note Object.hasOwn() (ES2022) replaces obj.hasOwnProperty(). It works even if the object was created with Object.create(null).

TSTypeScript

in Operator Guard

TS · Type Guards & Narrowing
syntax
if ("property" in value) { ... }
example
interface EmailContact {
  email: string;
  name: string;
}

interface PhoneContact {
  phone: string;
  name: string;
}

function sendMessage(contact: EmailContact | PhoneContact) {
  if ("email" in contact) {
    console.log(`Emailing ${contact.email}`);
  } else {
    console.log(`Calling ${contact.phone}`);
  }
}
output
// 'in' narrows based on the presence of a property

Note The 'in' operator checks if a property name exists on an object at runtime. TypeScript uses this to narrow union types. The property name must be a string literal for narrowing to work. Works well when union members have distinct unique properties.