前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TypeScript 官方手册翻译计划【八】:类型操控-按索引访问的类型

TypeScript 官方手册翻译计划【八】:类型操控-按索引访问的类型

作者头像
Chor
发布2021-12-06 08:20:35
4710
发布2021-12-06 08:20:35
举报
文章被收录于专栏:前端之旅前端之旅
  • 说明:目前网上没有 TypeScript 最新官方文档的中文翻译,所以有了这么一个翻译计划。因为我也是 TypeScript 的初学者,所以无法保证翻译百分之百准确,若有错误,欢迎评论区指出;
  • 翻译内容:暂定翻译内容为 TypeScript Handbook,后续有空会补充翻译文档的其它部分;
  • 项目地址TypeScript-Doc-Zh,如果对你有帮助,可以点一个 star ~

本章节官方文档地址:Indexed Access Type

按索引访问的类型

我们可以访问某个类型上的特定属性,从而获取该属性的类型。这种类型称为按索引访问的类型。

代码语言:javascript
复制
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
     ^^^
    // type Age = number

索引类型本身也是一个类型,所以它完全可以和联合类型、keyof 或者其它类型搭配使用:

代码语言:javascript
复制
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

如果尝试索引一个不存在的属性,则会抛出错误:

代码语言:javascript
复制
type I1 = Person["alve"];	
			    ^^^^^^			
// Property 'alve' does not exist on type 'Person'.

此外,我们还可以使用 number 获取数组元素的类型。我们可以将其与 typeof 相结合,方便地捕获数组字面量的元素类型:

代码语言:javascript
复制
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

你只能使用类型作为索引,也就是说,使用 const 创建的变量引用是不能作为索引的:

代码语言:javascript
复制
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'?
*/

不过,你可以改用类型别名重写这段代码:

代码语言:javascript
复制
type key = "agr";
type Age = Person[key];
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-11-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 按索引访问的类型
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档