跳到主要内容

ts常用工具函数

  • Parameters

  • ReturnType

  • NonNullable

  • Awaited

  • Pick

  • Omit

  • Partial

  • Required

  • Readonly

  • Record

  • Exclude

  • Extract

  • 字符串操作工具函数

    • Uppercase、Lowercase、Capitalize、Uncapitalize

Parameters​

  • 用于提取函数的参数类型
  • Parameters<T>
    • 获取函数类型 T 的参数类型组成的元组。

例子1:

ts
function createUser(name: string, age: number, email?: string) {
return { name, age, email }
}

// 获取函数参数类型
type CreateUserParams = Parameters<typeof createUser>
// 相当于: [string, number, string?]

// 使用示例:包装函数
function logAndCreateUser(...args: CreateUserParams) {
console.log('创建用户,参数:', args)
return createUser(...args)
}

例子2:

ts
type Options = {
a: number
b: number
}

function testFn(options: Options) {
return options
}

// 提取参数类型
const options: Parameters<typeof testFn>[0] = {
a: 1,
b: 2,
}

testFn(options)

ReturnType​

  • 获取函数的返回类型
  • ReturnType<T>
    • 获取函数类型 T 的返回值类型。
ts
function getUser() {
return {
id: 1,
name: 'John',
email: 'john@example.com'
}
}

// 获取函数返回类型
type GetUserReturn = ReturnType<typeof getUser>
// 相当于: { id: number; name: string; email: string }

// 使用示例:缓存返回值
const userCache: Map<number, ReturnType<typeof getUser>> = new Map()

function getUserWithCache(id: number): ReturnType<typeof getUser> {
if (userCache.has(id)) {
return userCache.get(id)!
}

const user = getUser()
userCache.set(id, user)
return user
}

// 实际应用:API 响应类型
async function fetchUserData() {
const response = await fetch('/api/user')
return response.json()
}

type UserData = ReturnType<typeof fetchUserData>
// 相当于: Promise<any>

Record​

  • 用于构造一个对象类型

  • Record<K, T>

    • 构造一个对象类型,属性键为 K,属性值为 T。
ts
// 基本用法
type Status = 'pending' | 'success' | 'error'
type StatusMessages = Record<Status, string>
// 相当于: { pending: string; success: string; error: string }

const messages: StatusMessages = {
pending: '处理中...',
success: '操作成功',
error: '操作失败'
}

// 实际应用:配置映射
type Theme = 'light' | 'dark'
type ThemeConfig = Record<Theme, {
backgroundColor: string
textColor: string
}>

const themeConfig: ThemeConfig = {
light: {
backgroundColor: '#ffffff',
textColor: '#000000'
},
dark: {
backgroundColor: '#000000',
textColor: '#ffffff'
}
}

NonNullable​

  • 排除类型的 null 和 undefined

  • NonNullable<T>

    • 从类型 T 中排除 null 和 undefined。
ts
type NullableString = string | null | undefined
type NonNullableString = NonNullable<NullableString>
// 相当于: string

// 实际应用:处理可能为空的值
function processValue(value: string | null | undefined): NonNullable<typeof value> {
if (value == null) {
throw new Error('Value cannot be null or undefined')
}
return value // 类型现在是 string
}

Awaited​

  • 获取promise类型的的值
    • 可以理解为获取 Promise 类型的解包类型。
    • 解包就是 取出promise的值
    • 取出最终的promise类型值
ts
// 1. 单层 Promise
type PromiseString = Promise<string>
type UnpackedString = Awaited<PromiseString>
// UnpackedString 现在是 string 类型

// 2. 嵌套 Promise
type NestedPromise = Promise<Promise<number>>
type UnpackedNumber = Awaited<NestedPromise>
// UnpackedNumber 现在是 number 类型(完全解包)

// 3. 三层嵌套
type DeeplyNested = Promise<Promise<Promise<boolean>>>
type UnpackedBoolean = Awaited<DeeplyNested>
// UnpackedBoolean 现在是 boolean 类型