避免代码重复和创建可重用类型是编写干净代码的重要部分。
type Add<T> = (a: T, b: T) => T
const addNumbers: Add<number> = (a, b) => {
return a + b
}
const addStrings: Add<string> = (a, b) => {
return a + b
}
将所有类型属性都设置为可选
type User = {
name: string
age: number
address: string
occupation: string
}
type PartialUser = Partial<User>
// type PartialUser = {
// name?: string;
// age?: number;
// address?: string;
// occupation?: string;
// }
Required 与 Partial 相反。它构造一个类型,其中需要该类型的所有属性。它可用于确保没有可选属性出现在类型中。
type PartialUser = {
name: string
age: number
address?: string
occupation?: string
}
type User = Required<PartialUser>
// type User = {
// name: string;
// age: number;
// address: string;
// occupation: string;
// }
多属性的对象中摘取某些属性。
键可以是字符串文字或字符串文字的并集。Keys 的值必须是 Type 的键,否则 TypeScript 编译器会报错。
type User = {
name: string
age: number
address: string
occupation: string
}
type BasicUser = Pick<User, "name" | "age">
// type BasicUser = {
// name: string;
// age: number;
// }
多属性的对象中剔除某些属性。
keys 不是关于保留哪些属性,而是要省略的属性键集。
type User = {
name: string
age: number
address: string
occupation: string
}
type BasicUser = Omit<User, "address" | "occupation">
// type BasicUser = {
// name: string;
// age: number;
// }
该类型的所有属性都设置为只读。给 TS 重新赋新值会报错。
type User = {
name: string
age: number
address: string
occupation: string
}
type ReadOnlyUser = Readonly<User>
const user: ReadOnlyUser = {
name: "Mark",
age: 34,
address: "Chicago",
occupation: "IT Engineer"
}
user.name = "Maxwell"
// Cannot assign to 'name' because it is a read-only property.
ReturnType 从函数类型的返回类型构造一个类型。当我们处理来自外部库的函数类型并希望基于它们构建自定义类型时,它很有用。
import axios from 'axios'
type Response = ReturnType<typeof axios>
function callAPI(): Response{
return axios("url")
}