Indexed access types of typescript



The official documents of typescript have long been updated, but the Chinese documents I can find are still in the older version. Therefore, some newly added and revised chapters are translated and sorted out.

This article is compiled from “typescript Handbook”Indexed Access Types“Chapter.

This article is not translated strictly according to the original text, and some contents are explained and supplemented.


We can useIndexed access typeFind a specific property on another type:

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

Because the index name itself is a type, we can also use unionkeyofOr 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 find a property that does not exist, typescript will report an error:

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

Next is another example, which we usenumberTo get the type of array element. combinationtypeofYou can easily capture the element types of array literals:

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

Only types can be used as indexes, which means you can’t use themconstCreate a variable reference:

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 use type aliases for similar Refactoring:

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

Finally, let’s talk about a practical case:

Suppose there is a business scenario in which a page needs to be used in different apps, such as Taobao, tmall and Alipay. The underlying APIs called will be different according to the app. We might write this:

const APP = ['TaoBao', 'Tmall', 'Alipay'];

function getPhoto(app: string) {
  // ...
getPhoto('TaoBao'); // ok
getPhoto('whatever'); // ok

If we just restrict the app tostringType. Even if other strings are passed in, there will be no error. We can use literal joint type constraints as follows:

const APP = ['TaoBao', 'Tmall', 'Alipay'];
type app = 'TaoBao' | 'Tmall' | 'Alipay';

function getPhoto(app: app) {
  // ...
getPhoto('TaoBao'); // ok
getPhoto('whatever'); // not ok

But writing twice is redundant. How can we get the string joint type of all its values according to an array? We can combine the previous articletypeofAnd the contents of this section:

const APP = ['TaoBao', 'Tmall', 'Alipay'] as const;
type app = typeof APP[number];
// type app = "TaoBao" | "Tmall" | "Alipay"

function getPhoto(app: app) {
  // ...
getPhoto('TaoBao'); // ok
getPhoto('whatever'); // not ok

Let’s analyze step by step:

The first is to useas constChange array toreadonlyTuple type:

const APP = ['TaoBao', 'Tmall', 'Alipay'] as const;
// const APP: readonly ["TaoBao", "Tmall", "Alipay"]

But at this timeAPPIt’s still a value. We passtypeofobtainAPPType of:

type typeOfAPP = typeof APP;
// type typeOfAPP = readonly ["TaoBao", "Tmall", "Alipay"]

Finally, access the type through the index to obtain the string union type:

type app = typeof APP[number];
// type app = "TaoBao" | "Tmall" | "Alipay"

Typescript series

Typescript series articles are composed of three parts: official document translation, key and difficult point analysis and practical skills, covering introduction, advanced and practical combat. It aims to provide you with a tutorial for systematically learning ts. the whole series is expected to be about 40.Click here to browse the full series of articles and suggest collecting sites by the way.

Wechat: “mqyqingfeng”, add me to Yu Yu’s only reader group.

If there is any mistake or lack of preciseness, please be sure to correct it. Thank you very much. If you like it or have some inspiration, welcome star, which is also an encouragement to the author.