微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[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;
}
*/

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐