86

I am trying to do something I am not sure is possible in TypeScript: inferring the argument types/return types from a function.

For example:

function foo(a: string, b: number) {
  return `${a}, ${b}`;
}

type typeA = <insert magic here> foo; // Somehow, typeA should be string;
type typeB = <insert magic here> foo; // Somehow, typeB should be number;

My use case is to try to create a config object that contains constructors and parameters.

For example:

interface IConfigObject<T> {
    // Need a way to compute type U based off of T.
    TypeConstructor: new(a: U): T;
    constructorOptions: U;
}

// In an ideal world, could infer all of this from TypeConstructor

class fizz {
    constructor(a: number) {}
}

const configObj : IConfigObj = {
    TypeConstructor: fizz;
    constructorOptions: 13; // This should be fine
}

const configObj2 : IConfigObj = {
    TypeConstructor: fizz;
    constructorOptions: 'buzz'; // Should be a type error, since fizz takes in a number
}

5 Answers 5

198

Typescript now has the ConstructorParameters builtin, similar to the Parameters builtin. Make sure you pass the class type, not the instance:

ConstructorParameters<typeof SomeClass>

ConstructorParameter Official Doc

Parameters Official Doc

4
  • 23
    Works great! If the constructor of SomeClass takes in an object as first argument, the syntax for getting the type of the object would be ConstructorParameters<typeof SomeClass>[0]
    – Mikey
    Commented Oct 11, 2019 at 9:19
  • 7
    But what about we have a generic param on SomeClass? I tried ConstructorParameters<typeof SomeClass<T>> but it turns out it's not valid syntax.
    – W.Leto
    Commented Apr 8, 2021 at 14:26
  • @W.Leto this appears to work fine from what I can see. Perhaps it's been fixed since you left your comment
    – devklick
    Commented Aug 21, 2023 at 15:45
  • 1
    @W.Leto if you're in a .tsx file then use this syntax: ConstructorParameters<typeof SomeClass<T,>>
    – Matthias
    Commented Aug 22, 2023 at 0:04
34

With TypeScript 2.8 you can use the new extends keyword:

type FirstArgument<T> = T extends (arg1: infer U, ...args: any[]) => any ? U : any;
type SecondArgument<T> = T extends (arg1: any, arg2: infer U, ...args: any[]) => any ? U : any;

let arg1: FirstArgument<typeof foo>; // string;
let arg2: SecondArgument<typeof foo>; // number;
let ret: ReturnType<typeof foo>; // string;
1
  • 1
    Is there any way to extract the argument type from an overloaded function?
    – csha
    Commented Nov 30, 2018 at 22:04
17

Typescript 2.8 added conditional types with type inference

Typescript 3.0 added rest-elements-in-tuple-types, so you can get all the arguments in an Array type now.

type ArgumentsType<T extends (...args: any[]) => any> = T extends (...args: infer A) => any ? A : never;

type Func = (a: number, b: string) => boolean;
type Args = ArgumentsType<Func> // type Args = [number, string];
type Ret = ReturnType<Func> // type Ret = boolean;

You can use it like this:

const func = (...args: Args): Ret => { // type the rest parameters and return type
  const [a, b] = args; // spread the arguments into their names
  console.log(a, b); // use the arguments like normal
  return true;
};

// Above is equivalent to:
const func: Func = (a, b) => {
  console.log(a, b);
  return true;
}
13

I'll throw in a more direct answer for the use case of extracting the constructor argument types.

type GetConstructorArgs<T> = T extends new (...args: infer U) => any ? U : never

class Foo {
    constructor(foo: string, bar: number){
        //
    }
}

type FooConstructorArgs = GetConstructorArgs<typeof Foo> // [string, number]
1

How about this approach:

interface IConfigObject<T, U> {
    TypeConstructor: new(a: U) => T;
    constructorOptions: U;
}

class fizz {
    constructor(a: number) {}
}

function createConfig<U, T>(cls: { new (arg: U): T }, arg: U): IConfigObject<T, U> {
    return {
        TypeConstructor: cls,
        constructorOptions: arg
    }
}

const configObj = createConfig(fizz, 3); // ok
const configObj2 = createConfig(fizz, "str"); // error

(code in playground)


Edit

You can have an indexed type variable:

const configs: { [name: string]: IConfigObject<any, any> } = {
    config1: createConfig(fizz, 3),
    config2: createConfig(fizz, "str"), // error
    config3: createConfig(buzz, "str")
}
2
  • 1
    This could definitely work. Is there any way to make it work as an index signature? For example: const configs : SomeType = { config1: { TypeConstructor: fizz, constructorOptions: 3, }, config2: { TypeConstructor: fizz, constructorOptions: 'str', // Should throw error } config3: { TypeConstructor: buzz, constructorOptions: 'str', } }
    – darpa
    Commented Apr 19, 2017 at 14:18
  • 1
    Sure. Check my revised answer Commented Apr 19, 2017 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.