Is there ArgumentsType like ReturnType in Typescript?

前端 未结 6 722
一个人的身影
一个人的身影 2020-11-30 12:34

ReturnType extracts return type of a function.

Is there a way to define ArgumentsType that extracts parameter types of a

6条回答
  •  盖世英雄少女心
    2020-11-30 13:04

    Edit

    Since writing the original answer, typescript now has a built-in type (defined in lib.d.ts) to get the type of the parameters called Parameters

    type argsEmpty = Parameters<() => void> // []
    type args = Parameters<(x: number, y: string, z: boolean) => void> // [number, string, boolean]
    type argsOpt = Parameters<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?]
    

    Edit Typescript 3.0 has been relesed the code below works as expected.

    While this is not possible in the current version of typescript (2.9) without spelling out all parameters. It will become possible in the next version of typescript (3.0) which will be released in the next few days:

    type ArgumentsType = T extends  (...args: infer U) => any ? U: never;
    
    type argsEmpty = ArgumentsType<() => void> // []
    type args = ArgumentsType<(x: number, y: string, z: boolean) => void> // [number, string, boolean]
    type argsOpt = ArgumentsType<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?]
    

    If you install npm install typescript@next you can already play with this, it should be available sometime this month.

    Note

    We can also spread a tuple into arguments with this new feature:

    type Spread = (...args: T)=> void;
    type Func = Spread //(x: number, y: string, z: boolean) => void
    

    You can read more about this feature here

提交回复
热议问题