Parameters
问题描述
实现内置的 Parameters 类型,而不是直接使用它,可参考TypeScript官方文档。
例如:
const foo = (arg1: string, arg2: number): void => {}
type FunctionParamsType = MyParameters<typeof foo> // [arg1: string, arg2: number]
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
const foo = (arg1: string, arg2: number): void => {}
const bar = (arg1: boolean, arg2: { a: 'A' }): void => {}
const baz = (): void => {}
type cases = [
Expect<Equal<MyParameters<typeof foo>, [string, number]>>,
Expect<Equal<MyParameters<typeof bar>, [boolean, { a: 'A' }]>>,
Expect<Equal<MyParameters<typeof baz>, []>>
]
// ============= Your Code Here =============
// 答案
type MyParameters<T extends (...args: any[]) => unknown> = T extends (...args: infer U) => unknown? U: never
最后一道简单题,实现内置类型 Parameters ,该类型是为了获取到函数的形参类型,并返回形参类型组成的数组类型,所以首先我们需要约束泛型参数为函数类型 T extends (...args: any[]) => any ,再使用三元表达式获取到函数的形参组成的类数组,即使用 infer 关键字将推断后的 any[]类数组存在泛型 U 中,(...args: infer U) => unknown,现在泛型 U 存着我们需要的形参类型组成的数组,返回 U 即可。