On this page
  1. keyof
  2. Syntax & Overview
  3. Notes & Pitfalls
  4. Example

keyof

Prev: `void` | Up: builtins | Next: `typeof`
Rel: builtins, Structural Typing & Narrowing
Ref: TypeScript Docs — keyof
Tags: #public #web #typescript #builtins #tier/core


Syntax & Overview

type UserKeys = keyof User;  // 'id' | 'email'

Produces a union of all public property keys (string, number, or symbol) of a type.

Notes & Pitfalls

Example

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

const port = getProp({ host: "localhost", port: 8080 }, "port"); // inferred as number

Linked from

Related notes