TypeScript高级类型备忘录(附示例)

本文介绍了TypeScript的高级类型,包括交叉类型、联合类型、泛型,以及Partial、Required、Readonly、Pick、Omit等内置类型。此外,还讲解了Extract、Exclude、Record、NonNullable映射类型和类型保护,如typeof、instanceof、in运算符。文章结尾提到,阅读原文有机会赢取五本TypeScript相关书籍。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接: 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 组合了两种类型: LeftTypeRightType ,并使用 符号构造交叉类型。

2. 联合类型

联合类型表示一个值可以是几种类型之一,例如某个函数希望传入 string 或者 number 类型的参数。

type UnionType = string | number

function showType(arg: UnionType) {
    console.log(arg)
}

showType("test")
// Output: test

showType(7)
// Output: 7

函数 showType 的参数是一个联合类型,它接受 stringnumber 作为参数。

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值