Skip to content

isKeyOf

Checks whether a value is a key of a given object. This type guard returns true if the key exists as an own property of obj. It supports both string and number keys. Symbols are excluded.

It never throws and never mutates input.

Signature

function isKeyOf<T extends Record<PropertyKey, unknown>>(
  obj: T,
  key: unknown
): key is keyof T

Parameters

Name Data type Description
object T The object to check keys against. Must be a non-null object.
key unknown The value to check as a potential key.

Returns

Boolean:

  • true: If key is a string or number that exists in obj as an own property.
  • false: Otherwise.

Behavior

  • Uses Object.prototype.hasOwnProperty to ensure the key is an own property.
  • Supports numeric keys (both number and string forms).
  • Rejects symbol keys.
  • Returns false if obj is null or not an object.
  • Returns false if key is not a string or number.

Examples

const obj = { a: 1, b: 2, 42: "answer" };

isKeyOf(obj, "a") // true
isKeyOf(obj, 42) // true
isKeyOf(obj, "c") // false
isKeyOf(obj, Symbol("x")) // false
isKeyOf(null, "a") // false

Notes

  • This is a semantic type guard; it does not coerce values.
  • Useful for safely checking keys before accessing object properties or performing transformations.
  • Pure, side-effect free, and never throws.