Skip to content

Latest commit

 

History

History
48 lines (30 loc) · 1.47 KB

File metadata and controls

48 lines (30 loc) · 1.47 KB

10. implement Parameters<T>

Problem

https://bigfrontend.dev/typescript/Parameters

Problem Description

For function type T, Parameters<T> returns a tuple type from the types of its parameters.

Please implement MyParameters<T> by yourself.

type Foo = (a: string, b: number, c: boolean) => string;

type A = MyParameters<Foo>; // [a:string, b: number, c:boolean]
type B = A[0]; // string
type C = MyParameters<{ a: string }>; // Error

Solution

type MyParameters<T extends Function> = T extends (...args: infer A) => any
  ? A
  : never;

Explanation

  • In the extends clause of a conditional type, we can use infer keyword to introduce a new type to be inferred. This inferred type can then be referenced in the true branch of the conditional type. For instance, with infer we can extract the return type of a function type:

    type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
  • (...arg: any[]) => any is a function type expression which is used to define types for functions.

Reference