Tipos de acesso indexado

Podemos usar um tipo de acesso indexado para buscar uma propriedade específica em outro tipo:

ts
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
type Age = number
Try

O tipo usado no índice também é um tipo, então podemos usar uniões, keyof ou qualquer outro tipo:

ts
type I1 = Person["age" | "name"];
type I1 = string | number
 
type I2 = Person[keyof Person];
type I2 = string | number | boolean
 
type AliveOrName = "alive" | "name";
type I3 = Person[AliveOrName];
type I3 = string | boolean
Try

Você verá um erro se tentar acessar uma propriedade que não existe:

ts
type I1 = Person["alve"];
Property 'alve' does not exist on type 'Person'.2339Property 'alve' does not exist on type 'Person'.
Try

Outro exemplo de indexação com um tipo qualquer é usar number para obter o tipo dos elementos de um array. Podemos combinar isso com typeof para capturar, de forma prática, o tipo dos elementos de um literal de array:

ts
const MyArray = [
{ name: "Alice", age: 15 },
{ name: "Bob", age: 23 },
{ name: "Eve", age: 38 },
];
 
type Person = typeof MyArray[number];
type Person = { name: string; age: number; }
type Age = typeof MyArray[number]["age"];
type Age = number
// Or
type Age2 = Person["age"];
type Age2 = number
Try

Você só pode usar tipos na indexação, ou seja, não é possível usar um const como referência de variável:

ts
const key = "age";
type Age = Person[key];
Type 'key' cannot be used as an index type.
'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?
2538
2749
Type 'key' cannot be used as an index type.
'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?
Try

No entanto, você pode usar um alias de tipo para fazer uma refatoração parecida:

ts
type key = "age";
type Age = Person[key];
Try

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

Contributors to this page:
OTOrta Therox  (5)
UMDFUlisses, Mago do Flutter  (1)

Last updated: Nov 16, 2026