Typescript 开发实用技巧清单
Typescript 在类型检查方面非常强大,但有时某些类型是其他类型的子集并且需要为它们定义类型检查时,它会变得乏味。
举个例子,有两种响应类型:
- 用户配置文件响应
interface UserProfileResponse {
id: number;
name: string;
email: string;
phone: string;
avatar: string;
}
- 登录响应
interface LoginResponse {
id: number;
name: string;
}
我们可以为 UserProfileResponse 定义类型并为 LoginResponse 选择一些属性,而不是定义相同上下文 LoginResponse 和 UserProfileResponse 的类型。
type LoginResponse = Pick<UserProfileResponse, "id" | "name">;
让我们了解一些可以帮助您编写更好代码的实用函数。
Uppercase
构造一个 Type 的所有属性都设置为大写的类型。
type Role = "admin" | "user" | "guest";
// Bad practice
type UppercaseRole = "ADMIN" | "USER" | "GUEST";
// Good practice
type UppercaseRole = Uppercase<Role>; // "ADMIN" | "USER" | "GUEST"
Lowercase
构造一个 Type 的所有属性都设置为小写的类型,与大写相反。
type Role = "ADMIN" | "USER" | "GUEST";
// Bad practice
type LowercaseRole = "admin" | "user" | "guest";
// Good practice
type LowercaseRole = Lowercase<Role>; // "admin" | "user" | "guest"
Capitalize
构造一个将 Type 的所有属性设置为大写的类型。
type Role = "admin" | "user" | "guest";
// Bad practice
type CapitalizeRole = "Admin" | "User" | "Guest";
// Good practice
type CapitalizeRole = Capitalize<Role>; // "Admin" | "User" | "Guest"
Uncapitalize
构造一个将 Type 的所有属性设置为 uncapitalize 的类型,与首字母大写相反。
type Role = "Admin" | "User" | "Guest";
// Bad practice
type UncapitalizeRole = "admin" | "user" | "guest";
// Good practice
type UncapitalizeRole = Uncapitalize<Role>; // "admin" | "user" | "guest"
Partial
构造一个类型,其中 Type 的所有属性都设置为可选。
interface User {
name: string;
age: number;
password: string;
}
// Bad practice
interface PartialUser {
name?: string;
age?: number;
password?: string;
}
// Good practice
type PartialUser = Partial<User>;
Required 构造一个类型,该类型由设置为 required 的 Type 的所有属性组成,Opposite的对面。
interface User {
name?: string;
age?: number;
password?: string;
}
// Bad practice
interface RequiredUser {
name: string;
age: number;
password: string;
}
// Good practice
type RequiredUser = Required<User>;
Readonly
构造一个类型,该类型由设置为只读的 Type 的所有属性组成。
interface User {
role: string;
}
// Bad practice
const user: User = { role: "ADMIN" };
user.role = "USER";
// Good practice
type ReadonlyUser = Readonly<User>;
const user: ReadonlyUser = { role: "ADMIN" };
user.role = "USER";
// Error: Cannot assign to 'role' because it is a read-only property.
Record
构造一个具有一组类型 T 的属性 K 的类型,每个属性 K 都映射到类型 T。
interface Address {
street: string;
pin: number;
}
interface Addresses {
home: Address;
office: Address;
}
// Alternative ✅
type AddressesRecord = Record<"home" | "office", Address>;
Pick
只选择键在联合类型键中的 Type 的属性。
interface User {
name: string;
age: number;
password: string;
}
// Bad practice
interface UserPartial {
name: string;
age: number;
}
// Good practice
type UserPartial = Pick<User, "name" | "age">;
Omit
Omit其键在联合类型键中的 Type 属性。
interface User {
name: string;
age: number;
password: string;
}
// Bad practice
interface UserPartial {
name: string;
age: number;
}
// Good practice
type UserPartial = Omit<User, "password">;
Exclude
构造一个具有 Type 的所有属性的类型,除了键在联合类型 Excluded 中的那些。
type Role = "ADMIN" | "USER" | "GUEST";
// Bad practice
type NonAdminRole = "USER" | "GUEST";
// Good practice
type NonAdmin = Exclude<Role, "ADMIN">; // "USER" | "GUEST"
Extract
构造一个具有 Type 的所有属性的类型,其键在联合类型 Extract 中。
type Role = "ADMIN" | "USER" | "GUEST";
// Bad practice
type AdminRole = "ADMIN";
// Good practice
type Admin = Extract<Role, "ADMIN">; // "ADMIN"
NonNullable
构造一个类型,其中 Type 的所有属性都设置为不可为空。
type Role = "ADMIN" | "USER" | null;
// Bad practice
type NonNullableRole = "ADMIN" | "USER";
// Good practice
type NonNullableRole = NonNullable<Role>; // "ADMIN" | "USER"
keyof
keyof 与 Object.keys 稍有相似,只是 keyof 采用了接口的键。
interface Point {
x: number;
y: number;
}
// type keys = "x" | "y"
type keys = keyof Point;
假设我们有一个如下所示的对象,我们需要使用 typescript 实现一个 get 函数来获取其属性的值。
const data = {
a: 3,
hello: 'max'
}
function get(o: object, name: string) {
return o[name]
}
- 我们一开始可能是这样写的,但它有很多缺点:
- 无法确认返回类型:这将失去 ts 的最大类型检查能力。
- 无法约束密钥:可能会出现拼写错误。
在这种情况下,可以使用 keyof 来增强 get 函数的 type 功能,有兴趣的可以查看 _.get 的 type 标签及其实现。
function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
return o[name]
}
必填&部分&选择
既然知道了keyof,就可以用它对属性做一些扩展,比如实现Partial和Pick,Pick一般用在_.pick中
type Partial<T> = {
[P in keyof T]?: T[P];
};
type Required<T> = {
[P in keyof T]-?: T[P];
};
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
interface User {
id: number;
age: number;
name: string;
};
// Equivalent to: type PartialUser = { id?: number; age?: number; name?: string; }
type PartialUser = Partial<User>
// Equivalent to: type PickUser = { id: number; age: number; }
type PickUser = Pick<User, "id" | "age">
这些类型内置在 Typescript 中。
条件类型
它类似于 ?: 运算符,你可以使用它来扩展一些基本类型。
T extends U ? X : Y
type isTrue<T> = T extends true ? true : false
// Equivalent to type t = false
type t = isTrue<number>
// Equivalent to type t = false
type t1 = isTrue<false>
never & Exclude & Omit
never 类型表示从不出现的值的类型。
结合 never 和条件类型可以引入许多有趣和有用的类型,例如 Omit
type Exclude<T, U> = T extends U ? never : T;
// Equivalent to: type A = 'a'
type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>
结合Exclude,我们可以介绍Omit的写作风格。
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
interface User {
id: number;
age: number;
name: string;
};
// Equivalent to: type PickUser = { age: number; name: string; }
type OmitUser = Omit<User, "id">
typeof
顾名思义,typeof代表一个取一定值的类型,下面的例子展示了它们的用法
const a: number = 3
// Equivalent to: const b: number = 4
const b: typeof a = 4
在一个典型的服务器端项目中,我们经常需要将一些工具塞进上下文中,比如config、logger、db models、utils等,然后使用typeof。
import logger from './logger'
import utils from './utils'
interface Context extends KoaContect {
logger: typeof logger,
utils: typeof utils
}
app.use((ctx: Context) => {
ctx.logger.info('hello, world')
// will return an error because this method is not exposed in logger.ts, which minimizes spelling errors
ctx.loger.info('hello, world')
})
.is
在此之前,我们先来看一个koa错误处理流程, 这是集中错误处理和识别代码的过程。
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
let code = 'BAD_REQUEST'
if (err.isAxiosError) {
code = `Axios-${err.code}`
} else if (err instanceof Sequelize.BaseError) {
}
ctx.body = {
code
}
}
})
在 err.code 中,它将编译错误,即“Error”.ts(2339) 类型上不存在属性“code”。
在这种情况下,可以使用 as AxiosError 或 as any 来避免错误,但是强制类型转换不够友好!
if ((err as AxiosError).isAxiosError) {
code = `Axios-${(err as AxiosError).code}`
}
在这种情况下,你可以使用 is 来确定值的类型。
function isAxiosError (error: any): error is AxiosError {
return error.isAxiosError
}
if (isAxiosError(err)) {
code = `Axios-${err.code}`
}
在 GraphQL 源代码中,有很多这样的用途来识别类型。
export function isType(type: any): type is GraphQLType;
export function isScalarType(type: any): type is GraphQLScalarType;
export function isObjectType(type: any): type is GraphQLObjectType;
export function isInterfaceType(type: any): type is GraphQLInterfaceType;
Record & Dictionary & Many
这些语法糖是从 lodash 的类型源代码中学习的,并且通常在工作场所中经常使用。
type Record<K extends keyof any, T> = {
[P in K]: T;
};
interface Dictionary<T> {
[index: string]: T;
};
interface NumericDictionary<T> {
[index: number]: T;
};
const data:Dictionary<number> = {
a: 3,
b: 4
}
用 const enum 维护 const 表
// Use objects to maintain consts
const TODO_STATUS {
TODO: 'TODO',
DONE: 'DONE',
DOING: 'DOING'
}
// Maintaining constants with const enum
const enum TODO_STATUS {
TODO = 'TODO',
DONE = 'DONE',
DOING = 'DOING'
}
function todos (status: TODO_STATUS): Todo[];
todos(TODO_STATUS.TODO)
VS Code 技巧和 Typescript 命令
时候用 VS Code,用 tsc 编译时出现的问题与 VS Code 提示的问题不匹配。
在项目的右下角找到Typescript字样,版本号显示在右侧,你可以点击它并选择Use Workspace Version,表示它始终与项目所依赖的typescript版本相同。
或编辑 .vs-code/settings.json
{
"typescript.tsdk": "node_modules/typescript/lib"
}
从字段到函数的推导
type Watcher<T> = {
// 避免key 为 symbols
on<K extends string & keyof T>(
eventName: `${K}Changed`,
callback: (oldValue: T[K], newValue: T[K] => void): void
)
}
declare function waatch<T>(obj: T): Watcher<T>
const prsonWatcher = watch({
fistName: 'man',
lasName: 'keung',
age: 18,
sex: '男'
})
personwatcher.on(
'ageChange',
(oldValue, newValue) => {}
)
infer封装通用类型工具
type Returen<T> = T extends (...args: any[]) => infer R ? R : T
type sum = (a: number, b: number) => number
type concat = (a: any[], b: any[]) => any[]
const sumResult: Return<sum> // number
const concatResult: Return<concat> // any[]
type PromiseType<T> = T extends Promise<infer K> ? K : T
type pt = PromiseType<Promise<string>> // string
type PromiseType<T> = T extends Promise<infer K> ? PromiseType<K> : T
type pt = PromiseType<Promise<Promise<string>>> // string
type FirstArg<T> = T extends (first: infer F, ...args: any[]) => any ? F : T
type fa = FirstArg<(name: string, age: number) => void> // string
type ArrayType<T> = T extends (infer I)[] ? I : T
type itemType1 = ArrayType<[string, number]> // string | number
type itemType2 = ArrayType<string[]> // string
ts中的递归类型推断
type Curried<A, R> => A extends []
? () => R
: A extends [infer ARG]
? (param: ARG) => R
: A extends [infer ARG, ...infer REST]
? (param: ARG) => Curried<REST, R>
: never;
declare function curry<A extends any[], R>(fn: (...args: A) => R): Curried<A, R>;
function sum(a: string, b: number) {
return 123
}
const currySum = curry(sum)
currySum('a')(1)({})
联合类型转交叉类型
type UnionToIntersection<T> =
(T extends any ? (x: T) => any : never) extends
(x: infer R) => any ? R : never;
type Test = {a: string} | {b: number} | {c: boolean}
type Test2 = UnionToIntersection<Test> // {a: string} & {b: number} & {c: boolean}
前置不定量参数
type JSTypeMap = {
'string': string,
'number': number,
'boolean': boolean,
'object': object,
'function': Function,
'symbol': symbol,
'undefined': undefined,
'bigint': bigint
}
type JSTypeName = keyof JSTypeMap
type ArgsType<T extends JSTypeName[]> = {
[I in keyof T]: JSTypeMap[T[I]]
}
declare function addImp<T extends JSTypeName>(
...args: [
...T,
(...args: ArgsType<T>) => any
]): void
addImp('number', 'string', 'boolean', (a, b, c) => {})