The keyof operator

The keyof operator can be used to generate a union type of the properties of an object as string literal types:

interface User {    name: string;    age: number;}type userKeys = keyof User; // "name" | "age"

The keyof operator can be used in combination with other operators, such as the typeof operator, for example:

let person = { name: "Remo", age: "28" };interface User {    name: string;    age: number;}type userKeys = keyof typeof person; // "name" | "age"

We will find out more about the keyof operator later in this chapter when we learn about lookup types.

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.