Search code examples
typescriptfunctiontype-parameter

is it possible to refer to a type when implementing a function with type parameters in typescript


I want to split the type specification and the implementation of a function in typescript

For example:

If I have a type like this

type MyFuncType = () => void

I can create an implementation that is an instance of that type like this:

const myFuncImp: MyFuncType = () => {
    //implementation
}

I now want to do this with type parameters. My approach does not work:

type MyFuncType<T> = () => void

const myFuncImp: MyFuncType = () => {
    //implementation
}

this results in a error:

Generic type 'MyFuncType' requires 1 type argument(s)

Is there another way to do this?


Solution

  • Attach the generic parameter to the function type instead of the type alias:

    type MyFuncType = <T>(a: string) => void;
    // instead of: type MyFuncType<T> = () => void;
    
    const myFuncImp: MyFuncType = <T>(a) => {
        //implementation
        const myArray: T[] = [];
        a.endsWith("foo")
    };