今天来介绍几个前端开发中经常用到的 TypeScript 的一些较新的功能和进展,这些也是我在日常工作中经常在用的功能。
在构造函数中直接定义属性
Typescript 中可以通过构造函数的参数直接定义属性,我们来先看早期的做法:
class Note {
public title: string;
public content: string;
private history: string[];
constructor(title: string, content: string, history: string[]) {
this.title = title;
this.content = content;
this.history = history;
}
}
采用 ts 中简写的语法:
class Note {
constructor(
public title: string,
public content: string,
private history: string[]
){
// 这里不用在写 this.title = title
}
}
它可能看上去不像是有属性的类,但它确实有,利用的是 Typescript 提供的简写形式 — 用构造函数的参数直接定义属性。
这个简写语法做了很多:
- 声明了一个构造函数参数及其类型
- 声明了一个同名的公共属性
- 当我们 new 出该类的一个实例时,把该属性初始化为相应的参数值
空值合并
??其实没啥意思,就是 Nullish Coalescing (空值合并)。听起来有点懵,我们直接上代码:
const i = undefined const k = i ?? 5 console.log(k) // 5 // 3.9.2 编译 const i = undefined; const k = i !== null && i !== void 0 ? i : 5; console.log(k); // 5
这个时候你肯定是想说了这样不就完了吗?
let k = i || 5
虽然这样也用,但是你不觉得很不严谨吗? 如果i = 0呢?
私有类字段
TypeScript 3.8 将支持 ECMAScript 私有字段,千万别和 TypeScript private 修饰符 混淆。
这是在 TypeScript 中具有私有类字段的类:
class Animal {
#name: string;
constructor(theName: string) {
this.#name = theName;
}
}
在private关键字之上使用私有类字段的区别在于前者有更好的运行时保证。用private关键字声明的 TypeScript 字段将在编译后的 JavaScript 代码中成为常规字段。另一方面,私有类字段在编译后的代码中仍然是私有的。
试图在运行时访问私有类字段将导致语法错误。我们也使用浏览器开发工具也检查不了私有类字段。
有了私有类字段,我们终于在 JavaScript 中得到了真正的隐私。
命名元组类型(Labeled tuple types)
命名元组类型适需要 TypeScript 4.0 及以上版本才能使用,它极大的改善了我们的开发体验及效率,先来看一个例子:
type Address = [string, number]
function setAddress(...args: Address) {
// some code here
console.log(args)
}
当我们这样定义函数入参后,在使用函数时,编辑器的智能提示只会提示我们参数类型,丢失了对参数含义的描述。

type User = {
name: string
age: number
location: string
}
type MyUser = Omit<User, 'name'>
以上就是我在前端开发中常用到的部分 TypeScript 特性,后续再分享其他,感谢阅读。