Skip to content

isPropertyKey

Checks if a value is a valid property key: string, number, or symbol.

Available since v2.0.3

import { isPropertyKey } from '@helpers4/guard';
// or, from the all-in-one package (same code, one install):
import { isPropertyKey } from 'helpers4/guard';
isPropertyKey(value: unknown): value is PropertyKey
ParameterTypeDescription
valueunknownThe value to check

value is PropertyKey — true if value can be used as an object property key

Strings, numbers, and symbols are valid property keys.

isPropertyKey('name')        // => true
isPropertyKey(42)            // => true
isPropertyKey(Symbol('id'))  // => true
isPropertyKey(null)          // => false
isPropertyKey(true)          // => false

Use as a guard before indexing an object with an unknown key.

function get(obj: Record<PropertyKey, unknown>, key: unknown): unknown {
  if (isPropertyKey(key)) return obj[key];
  return undefined;
}
get({ a: 1 }, 'a')    // => 1
get({ a: 1 }, null)   // => undefined

View source on GitHub