[Typescript] Index access types

Indexed Access types provide a mechanism for retrieving part(s) of an array or object type via indices. We’ll look at how this kind of type works, and a couple of practical examples of where you might use them.

interface Car {
  make: string
  model: string
  year: number
  color: {
    red: string
    green: string
    blue: string
  }
}

 

We can get color type:

let carColor: Car["color"]
/*
let carColor: {
    red: string;
    green: string;
    blue: string;
}
*/

 

We can get nested prop type:

let carColorRedComponent: Car["color"]["red"] // string

 

Index access type has safe guard:

let carColor: Car["not-something-on-car"] // ERROR: Property 'not-something-on-car' does not exist on type 'Car'.

 

We can get Intersection types on index access types:

let carPropertyWeInterest: Car["color" | "year", "model"]
/*
string | number | {
    red: string;
    green: string;
    blue: string;
}
*/

 

相关文章

我最大的一个关于TypeScript的问题是,它将原型的所有方法(无...
我对React很新,我正在尝试理解子组件之间相互通信的简洁方法...
我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,...
我发现接口非常有用,但由于内存问题我需要开始优化我的应用程...
我得到了一个json响应并将其存储在mongodb中,但是我不需要的...
我试图使用loadsh从以下数组中获取唯一类别,[{"listing...