Parameters
约 203 字小于 1 分钟
2026-02-11
题目
实现内置的 Parameters<T> 类型,而不是直接使用它,可参考TypeScript官方文档。
例如:
const foo = (arg1: string, arg2: number): void => {}
type FunctionParamsType = MyParameters<typeof foo> // [arg1: string, arg2: number]解题思路
使用 infer 关键字进行形式匹配。
答案
type MyParameters<T extends (...args: any[]) => any> = T extends (
...args: infer R
) => any ? R : never验证
function foo(arg1: string, arg2: number): void {}
function bar(arg1: boolean, arg2: { a: 'A' }): void {}
function baz(): void {}
type cases = [
Expect<Equal<MyParameters<typeof foo>, [string, number]>>,
Expect<Equal<MyParameters<typeof bar>, [boolean, { a: 'A' }]>>,
Expect<Equal<MyParameters<typeof baz>, []>>,
]