关于 TypeScript 的使用建议
Published by powerfulyang on Aug 30, 2023
优化 TypeScript 的性能
优先使用 interface 而非 type
我们都知道,type
与 interface
的作用非常相似
1interface Foo { prop: string }
2
3type Bar = { prop: string };
假设我们定义了多个不同的类型,interface
一般可使用 extends
来继承;而 type
需要使用交叉类型 &
来实现集成;
- 因为
interface
定义的是一个单一平面对象类型,可以检测属性是否冲突
1// interface 定义
2interface IA2 {
3 name: string
4}
5
6interface IB2 {
7 age: number
8}
9
10interface IC2 extends IA2, IB2{
11 // IC2 报错 Type 'number' is not assignable to type 'string'.
12 name: number
13}
14
15const interTest: IC2 = {
16 name: 1,
17 age: 2
18}
- 交叉类型只是递归的合并属性,有些情况下会产生
never
1// type 定义的交叉类型
2type IA2 {
3 name: string
4}
5
6type IB2 {
7 age: number
8}
9
10type C2 = A2 & B2 & { name: number }
11
12// 现在的 C2 类型的 name 会成为一个 never
13const test2: C2 = {
14 name: 1, //报错 Type 'number' is not assignable to type 'never'
15 age: 2
16}
所以当您可能需要将类型并集或交集时,请使用 interface
添加类型注解,尤其是返回类型,可以节省编译器的大量工作;
虽然 TypeScript 的 类型推导 是非常方便的,但是如果在一个大型项目中就会变得较慢,影响开发时间;
这是因为 命名类型(类型注解) 会比 匿名类型(类型推导) 让你的编译器减少了大量的读写声明文件的时间;
1//类型推导
2import { otherFunc } from "other';
3
4export function func() {
5 return otherFunc()
6}
7
8//类型注释
9import { otherFunc, OtherType } from 'other';
10
11export function func(): OtherType {
12 return otherFunc()
13}