原文链接: https://dev.to/ibrahima92/advanced-typescript-types-cheat-sheet-with-examples-5414
经作者授权后翻译
文末送五本书
TypeScript
是一种类型化的语言,允许你指定变量的类型,函数参数,返回的值和对象属性。
这里是一个带有示例的高级 TypeScript
类型备忘单。
1. 交叉类型
交叉类型是将多种类型组合为一种类型的方法。这意味着你可以将给定的类型A与类型B或更多类型合并,并获得具有所有属性的单个类型。
type LeftType = {
id: number
left: string
}
type RightType = {
id: number
right: string
}
type InterpType = LeftType & RightType
function showType(args: InterpType) {
console.log(args)
}
showType({
id: 1, left: "test", right: "test"
})
// Output: {id: 1, left: "test", right: "test"}
InterpType
组合了两种类型: LeftType
和 RightType
,并使用 &
符号构造交叉类型。
2. 联合类型
联合类型表示一个值可以是几种类型之一,例如某个函数希望传入 string
或者 number
类型的参数。
type UnionType = string | number
function showType(arg: UnionType) {
console.log(arg)
}
showType("test")
// Output: test
showType(7)
// Output: 7
函数 showType
的参数是一个联合类型,它接受 string
或 number
作为参数。
3.泛型
泛型是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。
function showType<T>(args: T) {
console.log(args)
}
showType("test")
// Output: "test"
showType(1)
// Output: 1
要构造泛型,需要使用尖括号并将 T
作为参数传递。
在这里,我使用 T
(名称自定义),然后使用不同的类型两次调用 showType
函数。
interface GenericType<T> {
id: number
name: T
}
function showType(args: GenericType<string>) {
console.log(args)
}
showType({ id: 1, name: "test" })
// Output: {id: 1, name: "test"}
function showTypeTwo(args: GenericType<number>) {
console.log(args)
}
showTypeTwo({ id: 1, name: 4 })
// Output: {id: 1, name: 4}
在这里,我们有另一个示例,该示例具有一个接口 GenericType
,该接口接收泛型 T
。由于它是可重用的,因此可以首先使用字符串,然后使用数字来调用它。
interface GenericType<T, U> {
id: T
name: U
}
function showType(args: GenericType<number, string>) {
console.log(args)
}
showType({ id: 1, name: "test" })
// Output: {id: 1, name: "test"}
function showTypeTwo(args: GenericType<string, string[]>) {
console.log(args)
}
showTypeTwo({ id: "001", name: ["This", "is", "a", "Test"] })
// Output: {id: "001", name: Ar