TypeScript全解:class(上)

为什么需要类呢? 外来人口多,迫切需要 class(以前是没有专门的前端的,都是其他方向转行来的) class 是保留字,迟早要实现 class 大部分人对原型的理解不够(因为大多数都语言是使用 class 来描述面向对象) 语法12345678910111213141516171819202122232425262728// 写法一class Po...

Read More

TypeScript全解:泛型编程(下)

开始逐渐体操化 先来看一些内置的 TS 工具 123456789type Person = { name: string; age: number; }type X1 = Readonly<Person>type X2 = Partial<Person>type X3 = Required<Person&...

Read More

TypeScript全解:泛型编程(上)

什么是泛型?泛,指多简单来说就是多种类型 只要你能看懂 JS 的函数,那么你就能看懂 TS 的泛型 JS: 12const fn = (a, b) => a + bconst result = fn(1,2) // 3 TS: 12type Fn<A, B> = A | Btype Result = Fn<string, num...

Read More

TypeScript全解:深入对象与函数(下)

函数重载(overload)什么是函数重载?简单来说就是同名的函数,这个概念是从 java 来的 我们来看这个需求,一个方法接受的参数有两种情况,可能是 number,可能是 string 如果用 TS 来实现,非常简单 12345class X { method(n: number | string) { /* ... */ ...

Read More

TypeScript全解:深入对象与函数(上)

深入对象索引签名(Index Signature)我们已经很熟悉了 12345678type Hash = { [key: stirng]: unknown; length: number;}type List { [key: number]: unknown; length: number;} 映射类型(M...

Read More

TypeScript全解:类型兼容

为什么要兼容? 因为实际工作中,往往无法类型一致 假设我们现在需要设计一个接受参数为 一个对象包涵3个属性 的函数,但实际数据缺拥有更多属性,我们很容易写出以下代码: 1234567const data = { a: 1, b: 2, c: 3, d: 4}const newData = lodash.pick(data, [&#x...

Read More

TypeScript全解:交叉类型

交叉类型(Intersection Types)(交集)1type A = string & number 很显然 A 的结果是 never,因为字符串和数字是两种完全不同的东西,所以一般交叉类型,我们不会用在普通类上 12345678type 有左手的人 = { left: string;}type 有右手的人 = ...

Read More

TypeScript全解:联合类型

JS 可以对值进行加减运算如果把 TS 的类型系统的当作一门语言,TS 可以对类型进行各种运算吗?如果有,那么 TS 类型系统有那些运算呢? 联合类型(union type)(也叫做并集)栗子🌰1234type A1 = number;type B1 = string;type C1 = A1 | B1;const c1: C1 = 42; 上述代码...

Read More

TypeScript全解:类型(下)

何时用enum类型当前端遇到这种需求的时候: 前端需要显示后端返回的状态 1,2,3,4,还要传输这个值回去, 但是我们经常会忘记这个值是什么意思,这个时候就可以使用 enum 🌰:二进制权限 1234567891011121314151617enum Permission { None = 0, Read = 1 << 0,...

Read More

TypeScript全解:类型(上)

JS/TS 中有哪些数据(data)类型(type) JS null, undefined, string, number, boolean, bigint, symbol, obejct(含 Array、Function、Date…) TS 以上所有,加上 void, never, enum, unknown, any,再加上自定义类型 ty...

Read More