Home > OS >  Getting the type of applied generic function
Getting the type of applied generic function

Time:03-24

In TypeScript, if I have a function, I can get the type of that function:

function foo(v: number) {}

type FooType = typeof foo; // RESULT: (v: number) => void

If I have a generic function, I can get the type of that function, and the type indicates that it is generic.

function foo<T>(v: T) {}

type FooType = typeof foo; // RESULT: <T>(v: T) => void

How can I get the type of the generic function when a known set of types is used? This doesn't work.

function foo<T>(v: T) {}

type FooNumberType = typeof foo<number>; // DESIRED: (v: number) => void
                               ^ error TS1005: ';' expected.

CodePudding user response:

This is not possible in Typescript 4.6 (the current release of as March 23, 2022). You cannot get the type of a generic function as if its generic was set to something.


However, your desired code works without modification in the unreleased Typescript 4.7.

See this playground which is set to use the nightly 4.7 build of Typescript.

See issue #47607 on "Instantiation Expressions" for more info about this change, which has this canonical example:

function makeBox<T>(value: T) {
    return { value };
};

const makeStringBox = makeBox<string>;  // (value: string) => { value: string }
const stringBox = makeStringBox('abc');  // { value: string }

const ErrorMap = Map<string, Error>;  // new () => Map<string, Error>
const errorMap = new ErrorMap();  // Map<string, Error>
  • Related