Operador de tipo keyof

O operador de tipo keyof

O operador keyof recebe um tipo de objeto e produz uma união de literais de string ou numéricos com as chaves dele. O tipo P a seguir é o mesmo tipo que type P = "x" | "y":

ts
type Point = { x: number; y: number };
type P = keyof Point;
type P = keyof Point
Try

Se o tipo tiver uma assinatura de índice string ou number, o keyof retorna esses tipos:

ts
type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
type A = number
 
type Mapish = { [k: string]: boolean };
type M = keyof Mapish;
type M = string | number
Try

Repare que, neste exemplo, M é string | number. Isso acontece porque as chaves de objetos em JavaScript são sempre convertidas para string, então obj[0] é sempre igual a obj["0"].

Os tipos criados com keyof ficam especialmente úteis quando combinados com tipos mapeados, que veremos com mais detalhes adiante.

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:
OTOrta Therox  (3)
UMDFUlisses, Mago do Flutter  (1)
RMRoman Mahotskyi  (1)
MMMasashi Miyazaki  (1)
Ssuica  (1)

Last updated: Nov 16, 2026