TypeScript 中提升幸福感的 10 个高级技巧

开发 前端
用了一年时间的 TypeScript 了,项目中用到的技术是 Vue + TypeScript 的,深感中大型项目中 TypeScript 的必要性,特别是生命周期比较长的大型项目中更应该使用 TypeScript。

用了一年时间的 TypeScript 了,项目中用到的技术是 Vue + TypeScript 的,深感中大型项目中 TypeScript 的必要性,特别是生命周期比较长的大型项目中更应该使用 TypeScript。

以下是我在工作中总结到的经常会用到的 TypeScript 技巧。

1. 注释

通过 /** */ 形式的注释可以给 TS 类型做标记提示,编辑器会有更好的提示:

  1. /** This is a cool guy. */ 
  2. interface Person { 
  3.   /** This is name. */ 
  4.   name: string, 
  5.  
  6. const p: Person = { 
  7.     name: 'cool' 

如果想给某个属性添加注释说明或者友好提示,这种是很好的方式了。

 

2. 接口继承

和类一样,接口也可以相互继承。

这让我们能够从一个接口里复制成员到另一个接口里,可以更灵活地将接口分割到可重用的模块里。

  1. interface Shape { 
  2.     color: string; 
  3.  
  4. interface Square extends Shape { 
  5.     sideLength: number; 
  6.  
  7. let square = <Square>{}; 
  8. square.color = "blue"
  9. square.sideLength = 10

一个接口可以继承多个接口,创建出多个接口的合成接口。

  1. interface Shape { 
  2.     color: string; 
  3.  
  4. interface PenStroke { 
  5.     penWidth: number; 
  6.  
  7. interface Square extends Shape, PenStroke { 
  8.     sideLength: number; 
  9.  
  10. let square = <Square>{}; 
  11. square.color = "blue"
  12. square.sideLength = 10
  13. square.penWidth = 5.0

3. interface & type

TypeScript 中定义类型的两种方式:接口(interface)和 类型别名(type alias)。

比如下面的 Interface 和 Type alias 的例子中,除了语法,意思是一样的:

Interface

  1. interface Point { 
  2.   x: number; 
  3.   y: number; 
  4.  
  5. interface SetPoint { 
  6.   (x: number, y: number): void

Type alias

  1. type Point = { 
  2.   x: number; 
  3.   y: number; 
  4. }; 
  5.  
  6. type SetPoint = (x: number, y: number) => void

而且两者都可以扩展,但是语法有所不同。此外,请注意,接口和类型别名不是互斥的。接口可以扩展类型别名,反之亦然。

Interface extends interface

  1. interface PartialPointX { x: number; } 
  2. interface Point extends PartialPointX { y: number; } 

Type alias extends type alias

  1. type PartialPointX = { x: number; }; 
  2. type Point = PartialPointX & { y: number; }; 

Interface extends type alias

  1. type PartialPointX = { x: number; }; 
  2. interface Point extends PartialPointX { y: number; } 

Type alias extends interface

  1. interface PartialPointX { x: number; } 
  2. type Point = PartialPointX & { y: number; }; 

它们的差别可以看下面这图或者看 TypeScript: Interfaces vs Types 。

所以檙想巧用 interface & type 还是不简单的。

如果不知道用什么,记住:能用 interface 实现,就用 interface , 如果不能就用 type 。

4. typeof

typeof 操作符可以用来获取一个变量或对象的类型。

我们一般先定义类型,再使用:

  1. interface Opt { 
  2.   timeout: number 
  3. const defaultOption: Opt = { 
  4.   timeout: 500 

有时候可以反过来:

  1. const defaultOption = { 
  2.   timeout: 500 
  3. type Opt = typeof defaultOption 

 

当一个 interface 总有一个字面量初始值时,可以考虑这种写法以减少重复代码,至少减少了两行代码是吧,哈哈~

5. keyof

TypeScript 允许我们遍历某种类型的属性,并通过 keyof 操作符提取其属性的名称。

keyof 操作符是在 TypeScript 2.1 版本引入的,该操作符可以用于获取某种类型的所有键,其返回类型是联合类型。

keyof 与 Object.keys 略有相似,只不过 keyof 取 interface 的键。

  1. const persion = { 
  2.   age: 3
  3.   text: 'hello world' 
  4.  
  5. // type keys = "age" | "text" 
  6. type keys = keyof Point; 

写一个方法获取对象里面的属性值时,一般人可能会这么写

  1. function get1(o: object, name: string) { 
  2.   return o[name]; 
  3.  
  4. const age1 = get1(persion, 'age'); 
  5. const text1 = get1(persion, 'text'); 

但是会提示报错

因为 object 里面没有事先声明的 key。

当然如果把 o: object 修改为 o: any 就不会报错了,但是获取到的值就没有类型了,也变成 any 了。

这时可以使用 keyof 来加强 get 函数的类型功能,有兴趣的同学可以看看 _.get 的 type 标记以及实现

  1. function get<T extends object, K extends keyof T>(o: T, name: K): T[K] { 
  2.   return o[name] 

6. 查找类型

  1. interface Person { 
  2.     addr: { 
  3.         city: string, 
  4.         street: string, 
  5.         num: number, 
  6.     } 

当需要使用 addr 的类型时,除了把类型提出来

  1. interface Address { 
  2.     city: string, 
  3.     street: string, 
  4.     num: number, 
  5.  
  6. interface Person { 
  7.     addr: Address, 

还可以

  1. Person["addr"// This is Address. 

比如:

  1. const addr: Person["addr"] = { 
  2.     city: 'string'
  3.     street: 'string'
  4.     num: 2 

有些场合后者会让代码更整洁、易读。

7. 查找类型 + 泛型 + keyof

泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。

  1. interface API { 
  2.     '/user': { name: string }, 
  3.     '/menu': { foods: string[] } 
  4. const get = <URL extends keyof API>(url: URL): Promise<API[URL]> => { 
  5.     return fetch(url).then(res => res.json()); 
  6.  
  7. get(''); 
  8. get('/menu').then(user => user.foods); 

 

8. 类型断言

Vue 组件里面经常会用到 ref 来获取子组件的属性或者方法,但是往往都推断不出来有啥属性与方法,还会报错。

子组件:

  1. <script lang="ts"
  2. import { Options, Vue } from "vue-class-component"
  3.  
  4. @Options({ 
  5.   props: { 
  6.     msg: String, 
  7.   }, 
  8. }) 
  9. export default class HelloWorld extends Vue { 
  10.   msg!: string; 
  11. </script> 

父组件:

  1. <template> 
  2.   <div class="home"
  3.     <HelloWorld 
  4.       ref="helloRef" 
  5.       msg="Welcome to Your Vue.js + TypeScript App" 
  6.     /> 
  7.   </div> 
  8. </template> 
  9.  
  10. <script lang="ts"
  11. import { Options, Vue } from "vue-class-component"
  12. import HelloWorld from "@/components/HelloWorld.vue"// @ is an alias to /src 
  13.  
  14. @Options({ 
  15.   components: { 
  16.     HelloWorld, 
  17.   }, 
  18. }) 
  19. export default class Home extends Vue { 
  20.   print() { 
  21.     const helloRef = this.$refs.helloRef; 
  22.     console.log("helloRef.msg: ", helloRef.msg);  
  23.   } 
  24.  
  25.   mounted() { 
  26.     this.print(); 
  27.   } 
  28. </script> 

因为 this.$refs.helloRef 是未知的类型,会报错误提示:

做个类型断言即可:

  1. print() { 
  2.     // const helloRef = this.$refs.helloRef; 
  3.     const helloRef = this.$refs.helloRef as any; 
  4.     console.log("helloRef.msg: ", helloRef.msg); // helloRef.msg:  Welcome to Your Vue.js + TypeScript App 
  5.   } 

但是类型断言为 any 时是不好的,如果知道具体的类型,写具体的类型才好,不然引入 TypeScript 冒似没什么意义了。

9. 显式泛型

$('button') 是个 DOM 元素选择器,可是返回值的类型是运行时才能确定的,除了返回 any ,还可以

  1. function $<T extends HTMLElement>(id: string): T { 
  2.     return (document.getElementById(id)) as T; 
  3.  
  4. // 不确定 input 的类型 
  5. // const input = $('input'); 
  6.  
  7. // Tell me what element it is. 
  8. const input = $<HTMLInputElement>('input'); 
  9. console.log('input.value: ', input.value); 

函数泛型不一定非得自动推导出类型,有时候显式指定类型就好。

10. DeepReadonly

被 readonly 标记的属性只能在声明时或类的构造函数中赋值。

之后将不可改(即只读属性),否则会抛出 TS2540 错误。

与 ES6 中的 const 很相似,但 readonly 只能用在类(TS 里也可以是接口)中的属性上,相当于一个只有 getter 没有 setter 的属性的语法糖。

下面实现一个深度声明 readonly 的类型:

  1. type DeepReadonly<T> = { 
  2.   readonly [P in keyof T]: DeepReadonly<T[P]>; 
  3.  
  4. const a = { foo: { bar: 22 } } 
  5. const b = a as DeepReadonly<typeof a> 
  6. b.foo.bar = 33 // Cannot assign to 'bar' because it is a read-only property.ts(2540) 

 

责任编辑:张燕妮 来源: segmentfault.com
相关推荐

2020-05-22 18:19:34

微服务架构

2017-11-30 19:23:24

2017-12-19 11:54:51

微信朋友圈同步

2012-07-12 13:20:35

职场生活程序员

2022-12-12 08:29:59

Vite构建工具

2011-04-06 12:22:28

2018-03-21 08:39:14

2017-03-29 13:12:56

Windows工具资讯

2019-04-12 08:19:15

快手AI算法

2022-12-07 14:40:39

能源

2012-01-11 14:58:08

2019-02-26 14:23:06

跳槽薪资职业

2022-11-07 16:06:15

TypeScript开发技巧

2017-10-30 15:22:29

代码可读性技巧

2019-09-26 08:33:51

Nginx技术Java

2017-11-06 14:33:54

Web开发服务器网络

2020-11-02 14:17:29

VsCode 插件

2020-05-20 13:06:20

UI排版设计
点赞
收藏

51CTO技术栈公众号