How to "fill in" generic parameter in typescript

Issue

Let’s say I have a generic typescript function like this:

function doThing<T>(param: T): T {
    //...
}

And I have a concrete interface like this:

interface MyType {
    x: string;
    y: number;
}

I want to re-export doThing method so that it assumes generic parameter T is always MyType. The reason is so that I can type something like:

doThing({

…and editor will auto-complete members x and y without me having to specify T in advance.

I know I can do something like:

import {doThing as _doThing} from 'some-module';
export const doThing = _doThing as (param: MyType) => MyType;

However, this is cumbersome and error prone. Also, doThing actually has a lot more members and variants than in this simplified example, so it would take a lot of copy-pasting.

Is there a way to simply "fill in" T, without having to copy-paste the entire original definition?

Solution

The code below is allowed since TypeScript 4.7.

const foo: typeof doThing<MyType> = doThing

Answered By – umitu

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.