首页 > 其他分享 >[Typescript] Index access types

[Typescript] Index access types

时间:2022-08-16 21:23:20浏览次数:78  
标签:Index Typescript string color Car access let type 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;
}
*/

 

标签:Index,Typescript,string,color,Car,access,let,type,types
From: https://www.cnblogs.com/Answer1215/p/16593025.html

相关文章