Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Check If a Key Exists in a TypeScript Object

Use `in` for runtime presence and narrowing, an own-property check to exclude inherited keys, and `keyof` for compile-time key constraints.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use key in obj to check at runtime whether a property exists on an object or anywhere in its prototype chain. For an own-property-only check, use Object.prototype.hasOwnProperty.call(obj, key). If you instead need to restrict a key to properties declared by a type, use K extends keyof T—that is a compile-time constraint, not a runtime existence check.

Choose the check that matches your question

What you need to know Use What it establishes
Does the property exist on this value or its prototype chain? key in obj Runtime presence, and TypeScript control-flow narrowing.
Is the property directly stored on this object? Object.prototype.hasOwnProperty.call(obj, key) Runtime own-property presence; inherited properties do not count.
Is this key allowed by the declared type? K extends keyof T A compile-time restriction to keys represented by T; it does not inspect an object at runtime.
Can this dictionary be indexed by a dynamic key? An index signature or dictionary type Describes the type of values for supported keys, not whether a particular entry is populated.

Check runtime presence with in

Use in when a key is available at runtime and you want TypeScript to narrow an object union based on that check:

As an Amazon Associate I earn from qualifying purchases.

type User = { name: string };
type Job = { title: string };

function describe(value: User | Job): string {
  if ("name" in value) {
    return value.name;
  }
  return value.title;
}

The operator checks the object and its prototype chain. A successful result therefore means the property is available through the object, not necessarily that it is an own property.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Optional properties can fit both branches

If a union member declares a property as optional, it may remain possible in both branches of an in check. The true branch alone does not prove that the property was required in the original type. Check the value as needed before relying on it.

Presence does not validate the value

A property can exist and still hold undefined or a value of an unexpected type. Since TypeScript 4.9, an in check for a property not listed on the known type can narrow the object to include that property as unknown. Validate the value before treating it as a specific type. See the TypeScript 4.9 release notes.

Check untrusted data safely

When a value begins as unknown, first establish that it is a non-null object, then check for the property and validate its value:

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
function readName(value: unknown): string | undefined {
  if (value !== null && typeof value === "object" && "name" in value) {
    const name = value.name;
    return typeof name === "string" ? name : undefined;
  }
  return undefined;
}

The in expression establishes property presence; the typeof check establishes that the value is a string. Keep these checks separate when handling data whose shape is not trusted.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Require an own property

If inherited properties must not count—for example, when checking data that should be directly present on the object—use an own-property check:

if (Object.prototype.hasOwnProperty.call(obj, key)) {
  // key is an own property of obj
}

This is JavaScript’s own-property check, not a TypeScript-specific operator. The distinction matters because in also returns true for inherited properties.

Restrict keys using keyof

Use keyof T when the question is whether a key belongs to a declared type, or when writing a generic helper that should accept only keys of that type:

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

Here, K extends keyof T rejects keys not represented by T, and T[K] preserves the relationship between the selected key and its value type. This is a static constraint: it does not prove that an optional property has a non-undefined value at runtime.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Depending on the object type, keyof T can include string, number, and symbol keys. Do not assume a generic key is always a string unless the helper explicitly restricts it. This behavior is covered in the TypeScript 2.9 release notes.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use an index signature for dynamic dictionaries

An index signature describes values accessible through arbitrary supported keys, but it does not guarantee that every possible key has an entry. For example:

type Scores = { [name: string]: number };

const scores: Scores = { Ada: 10 };
const value = scores["Grace"]; // The type depends on compiler options

With noUncheckedIndexedAccess enabled, reads from possibly absent indexed keys include undefined in their type. The option was introduced in TypeScript 4.1; see the TypeScript 4.1 release notes. Use an explicit runtime presence check when you need to know whether a particular dictionary entry exists.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.