← All languages
TypeScript construct of the day
Random

PropertyKey

Type representing all valid property key types: string, number, or symbol.

Description

PropertyKey is a built-in type alias for string | number | symbol, representing all types that can be used as object property keys in JavaScript. It is the type of the first parameter to functions like Object.defineProperty and Reflect.get.

PropertyKey is useful as a constraint for generic type parameters that represent object keys, especially when the key could be any of the three key types. It is more permissive than keyof, which produces specific literal types from a known object type.

This type is part of TypeScript's standard library and is used throughout the built-in type definitions for Object, Proxy, Reflect, and other APIs that work with arbitrary property keys.

Example

function getProperty(obj: object, key: PropertyKey): unknown {
  return (obj as any)[key];
}

const sym = Symbol('id');
const user = { name: 'Alice', age: 30, [sym]: 123 };

getProperty(user, 'name');  // string key
getProperty(user, sym);     // symbol key

function hasKey<T extends object>(obj: T, key: PropertyKey): key is keyof T {
  return key in obj;
}

Reference