前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TypeScript系列教程九《类型转换》-- 索引访问类型

TypeScript系列教程九《类型转换》-- 索引访问类型

作者头像
星宇大前端
发布2021-08-05 16:16:27
6510
发布2021-08-05 16:16:27
举报
文章被收录于专栏:大宇笔记大宇笔记

类型转换是TS最好玩也是语言的灵魂,想玩好需要熟练各种手段和工具,下面一一介绍类型转换的一些常用手段。

索引访问类型


我们可以使用索引访问类型查找其他类型的特定属性:

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

//type Age = number

类型的索引访问类型,我们可以使用联合类型,keyof 或者 其他type:

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

如果index属性不存在的话,TS会报错

代码语言: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
  // Or
  type Age2 = Person["age"];
        
//   type Age2 = number

索引是了个类型,我不能用变量去代替。

代码语言:javascript
复制
const key = "age";
type Age = Person[key];
//Type 'any' 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 = "age";
type Age = Person[key];
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-08-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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