1
  • Description : There is currently no Chinese translation of the latest official documents of TypeScript on the Internet, so there is such a translation plan. Because I am also a beginner in TypeScript, I cannot guarantee that the translation will be 100% accurate. If there are errors, please point out in the comment section;
  • translation content : The tentative translation content is TypeScript Handbook , and other parts of the translation document will be added later;
  • project address : TypeScript-Doc-Zh , if it helps you, you can click a star~

The official document address of this chapter: Indexed Access Type

Types of access by index

We can access a specific attribute on a type to obtain the type of the attribute. This type is called the type accessed by index.

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

The index type itself is also a type, so it can be used with union types, keyof or other types:

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

If you try to index a non-existent attribute, an error will be thrown:

type I1 = Person["alve"];    
                ^^^^^^            
// Property 'alve' does not exist on type 'Person'.

In addition, we can also use number get the type of array elements. We can combine it with typeof to easily capture the element type of the array literal:

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
// 或者
type Age2 = Person["age"];
     ^^^ 
    // type Age2 = number

You can only use type as an index, that is, const cannot be used as indexes:

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'?
*/

However, you can rewrite this code using type aliases instead:

type key = "agr";
type Age = Person[key];

Chor
2k 声望5.9k 粉丝