关于SegmentFault:TypeScript-中提升幸福感的-10-个高级技巧

8次阅读

共计 4733 个字符,预计需要花费 12 分钟才能阅读完成。

用了一年工夫的 TypeScript 了,我的项目中用到的技术是 Vue + TypeScript 的,深感中大型项目中 TypeScript 的必要性,特地是生命周期比拟长的大型项目中更应该应用 TypeScript。

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

1. 正文

通过 /** */ 模式的正文能够给 TS 类型做标记提醒,编辑器会有更好的提醒:

/** This is a cool guy. */
interface Person {
  /** This is name. */
  name: string,
}

const p: Person = {name: 'cool'}

如果想给某个属性增加正文阐明或者敌对提醒,这种是很好的形式了。

2. 接口继承

和类一样,接口也能够互相继承。

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

interface Shape {color: string;}

interface Square extends Shape {sideLength: number;}

let square = <Square>{};
square.color = "blue";
square.sideLength = 10;

一个接口能够继承多个接口,创立出多个接口的合成接口。

interface Shape {color: string;}

interface PenStroke {penWidth: number;}

interface Square extends Shape, PenStroke {sideLength: number;}

let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;

3. interface & type

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

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

Interface

interface Point {
  x: number;
  y: number;
}

interface SetPoint {(x: number, y: number): void;
}

Type alias

type Point = {
  x: number;
  y: number;
};

type SetPoint = (x: number, y: number) => void;

而且两者都能够扩大,然而语法有所不同。此外,请留神,接口和类型别名不是互斥的。接口能够扩大类型别名,反之亦然。

Interface extends interface

interface PartialPointX {x: number;}
interface Point extends PartialPointX {y: number;}

Type alias extends type alias

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

Interface extends type alias

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

Type alias extends interface

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

它们的差异能够看上面这图或者看 TypeScript: Interfaces vs Types。

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

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

4. typeof

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

咱们个别先定义类型,再应用:

interface Opt {timeout: number}
const defaultOption: Opt = {timeout: 500}

有时候能够反过来:

const defaultOption = {timeout: 500}
type Opt = typeof defaultOption

当一个 interface 总有一个字面量初始值时,能够思考这种写法以缩小反复代码,至多缩小了两行代码是吧,哈哈~

5. keyof

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

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

keyofObject.keys 略有类似,只不过 keyofinterface 的键。

const persion = {
  age: 3,
  text: 'hello world'
}

// type keys = "age" | "text"
type keys = keyof Point;

写一个办法获取对象外面的属性值时,个别人可能会这么写

function get1(o: object, name: string) {return o[name];
}

const age1 = get1(persion, 'age');
const text1 = get1(persion, 'text');

然而会提醒报错

因为 object 外面没有当时申明的 key。

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

这时能够应用 keyof 来增强 get 函数的类型性能,有趣味的同学能够看看 _.gettype 标记以及实现

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

6. 查找类型

interface Person {
    addr: {
        city: string,
        street: string,
        num: number,
    }
}

当须要应用 addr 的类型时,除了把类型提出来

interface Address {
    city: string,
    street: string,
    num: number,
}

interface Person {addr: Address,}

还能够

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

比方:

const addr: Person["addr"] = {
    city: 'string',
    street: 'string',
    num: 2
}

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

7. 查找类型 + 泛型 + keyof

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

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

get('');
get('/menu').then(user => user.foods);

8. 类型断言

Vue 组件外面常常会用到 ref 来获取子组件的属性或者办法,然而往往都推断不进去有啥属性与办法,还会报错。

子组件:

<script lang="ts">
import {Options, Vue} from "vue-class-component";

@Options({
  props: {msg: String,},
})
export default class HelloWorld extends Vue {msg!: string;}
</script>

父组件:

<template>
  <div class="home">
    <HelloWorld
      ref="helloRef"
      msg="Welcome to Your Vue.js + TypeScript App"
    />
  </div>
</template>

<script lang="ts">
import {Options, Vue} from "vue-class-component";
import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src

@Options({
  components: {HelloWorld,},
})
export default class Home extends Vue {print() {
    const helloRef = this.$refs.helloRef;
    console.log("helloRef.msg:", helloRef.msg); 
  }

  mounted() {this.print();
  }
}
</script>

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

做个类型断言即可:

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

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

9. 显式泛型

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

function $<T extends HTMLElement>(id: string): T {return (document.getElementById(id)) as T;
}

// 不确定 input 的类型
// const input = $('input');

// Tell me what element it is.
const input = $<HTMLInputElement>('input');
console.log('input.value:', input.value);

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

10. DeepReadonly

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

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

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

上面实现一个深度申明 readonly 的类型:

type DeepReadonly<T> = {readonly [P in keyof T]: DeepReadonly<T[P]>;
}

const a = {foo: { bar: 22} }
const b = a as DeepReadonly<typeof a>
b.foo.bar = 33 // Cannot assign to 'bar' because it is a read-only property.ts(2540)

最初

大佬们,感觉有用就赞一个呗。

挺久没写原创技术文章了,作为 2021 第一篇原创技术文章,品质应该还能够吧 ????

笔者的年终总结在这里:前端工程师的 2020 年终总结 – 乾坤未定,你我皆黑马,心愿能带给你一点启发。

参考文章:

  • TypeScript 高级技巧
  • 巧用 Typescript
  • 巧用 Typescript (二)
  • 接口

举荐浏览

  • 前端工程师的 2019 年终总结 – 当勤精进,但念无常
  • 前端工程师的 2018 年终总结 – 我的本命年
正文完
 0