百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

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

ztj100 2025-03-14 22:36 15 浏览 0 评论

来源:segmentfault.com

用了一年时间的 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.color = "blue";

square.sideLength = 10;

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

interface Shape {

color: string;

}


interface PenStroke {

penWidth: number;

}


interface Square extends Shape, PenStroke {

sideLength: number;

}


let 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 版本引入的,该操作符可以用于获取某种类型的所有键,其返回类型是联合类型。

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

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函数的类型功能,有兴趣的同学可以看看 _.get的 type 标记以及实现

function get(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: URL): Promise => {

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>

父组件:


<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 $(id: string): T {

return (document.getElementById(id)) as T;

}


// 不确定 input 的类型

// const input = $('input');


// Tell me what element it is.

const input = $('input');

console.log('input.value: ', input.value);

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

10. DeepReadonly

被 readonly标记的属性只能在声明时或类的构造函数中赋值。之后将不可改(即只读属性),否则会抛出 TS2540 错误。与 ES6 中的 const很相似,但 readonly只能用在类(TS 里也可以是接口)中的属性上,相当于一个只有 getter没有 setter的属性的语法糖。下面实现一个深度声明 readonly的类型:

type DeepReadonly = {

readonly [P in keyof T]: DeepReadonly;

}


const a = { foo: { bar: 22 } }

const b = a as DeepReadonly

b.foo.bar = 33 // Cannot assign to 'bar' because it is a read-only property.ts(2540)

相关推荐

你不知道的PostgreSQL数据库安装及实现跨库查询PG和Oracle

PG作为近几年最火热的关系型数据,已经被很多开发者所使用,尤其是5G网络普及完毕后,IOT和AI的应用场景下,数据的读写速度要求非常高,MYSQL已经开始不能满足高强度的数据吞吐(这里有争议,这里只是...

从小白到专家 PG技术大讲堂 - Part 3:PG建库与使用

PostgreSQL从小白到专家,是从入门逐渐能力提升的一个系列教程,内容包括对PG基础的认知、包括安装使用、包括角色权限、包括维护管理、、等内容,希望对热爱PG、学习PG的同学们有帮助,欢迎持续关注...

最全总结,聊聊 Python 数据处理全家桶(PgSQL篇)

来源:AirPython作者:星安果1.前言大家好,我是安果!PgSQL,全称为PostgreSQL,是一款免费开源的关系型数据库相比最流行的Mysql数据库,PgSQL在可靠性、数据完整性...

Excel函数的基本知识和使用,带你迅速掌握函数,可直接套用!

文章最后有彩蛋!好礼相送!...

Excel 小计、总计公式全都能自动计算新增行,套路公式存好

很多同学会觉得Excel单个案例讲解有些碎片化,初学者未必能完全理解和掌握。不少同学都希望有一套完整的图文教学,从最基础的概念开始,一步步由简入繁、从入门到精通,系统化地讲解Excel的各个知...

Excel查找最后一条记录,3种方法,你会么?

举一个工作中的例子,左边是商品的出库记录,其中的两列数据,现在需要快速找出最后一次出库的时间1、vlookup公式因为每种商品都会有多条出库记录,所以当我们使用vlookup公式时,它只会查找匹配到第...

DeepSeek装进IDEA,全网最全操作指南一篇详解!编程效率大幅提升

在IDEA插件中搜索“通义灵码”,即可获取到AI插件:点击“Install”按钮即可快速安装:安装可能需要一点点时间,等待即可。安装成功以后,在IDEA窗口的右下角,会提示你登录“...

Excel快速合并内容并换行(excel怎么合并后换行)

#一张图记录元旦假期#...

(六)MyBatis面试通关宝典:让你在面试中脱颖而出的关键

一、MyBatis中的工作原理...

Excel数据透视表,逆透视,你会么?

举个工作中的例子来说明,老板发给你左边的表格,让你快速转换成右边的样式,如下所示:1、数据透视表正常情况下,我们都是从右边的数据明细,使用数据透视表,得到左边的结果,简单回顾一一下,我们选中数据区域,...

掌握 Excel 「删除重复项」的4种方法,少做 80%的无用功!

在Excel中,删除重复项是数据清理和整理的常见任务,有多种方法可以实现这一目标。...

一分钟教会你在Excel里面接入DeepSeek,我们一起帮哪吒逆天改命

01...

128G手机还能用两年!微信这新功能突然来了

爽啊,微信最近搞了两个实用性拉满的新功能。不知道大伙有没有碰上过这么个情况。...

Vlookup公式用法大全,建议收藏备用

上班打工人必学的VLOOKUP函数公式,花费2个小时,总结全了,一起来学1、VLOOKUP公式基本用法VLOOKUP公式有4个参数,使用用法:=VLOOKUP(查找值,查找区域,返回第几列,查找方式)...

mariadb数据库使用SQL命令操作表-增删改查

1.DML基础语法DML(DataManipulationLanguage)...

取消回复欢迎 发表评论: