如今不管是前端,仍是基于Node.js的后端,对TypeScript的使用愈来愈多。今天咱们说一个TypeScript高级使用技巧——提取已有对象的类型。javascript
在ts中,一般咱们是先声明类型,再建立该类型的对象:前端
type User = { name: string, age: number } const me: User = { name: 'Youmoo', age: 18 };
在某些状况下咱们并不知道一个对象的类型,(如引用三方库的对象,而三方库并无暴露该对象的类型时)java
咱们能够借助ts,让它帮咱们推断出对象类型:后端
const animal = { type: 'cat', name: 'Tom' }; // 对于以上对象,咱们须要提取出它的类型,并建立一个同类型的对象 type Animal = typeof animal; // 定义一个同类型的对象 const mouse: Animal = { type: 'mouse', name: 'Jerry' };
在visual studio code中,能够看到ts帮咱们正确地推导出了Animal类型:数组
以上是简单的object对象,若咱们想提取数组内元素的类型呢?微信
方法有多种。spa
1、利用下标提取元素类型3d
type Animals = Array<{ type: string, name: string }>; type Animal = Animals[number];
2、利用conditional+infercode
type Animals = Array<{ type: string, name: string }>; type Animal = Animals extends (infer T)[] ? T : never;
有了以上技巧,能够引出一些有意思的玩法。对象
好比,将string数组中的元素提取为常量类型。
const valid_answers = ['yes', 'no', 'answer'] as const; type Answer = (typeof valid_answers)[number]; const ans1: Answer = 'yes';// 没问题 const ans2: Answer = 'nope';// 编译不经过
其中Answer的类型定义是:
咱们甚至能够继续向内,提取更深层的字段类型:
type Foo = { x: Array<{ y: string }> }; type TypeY = Foo['x'][number]['y'];
你说,TypeY是什么类型呢?
本文初发布于微信公众号 背井(nineteen84)。扫码可关注。