Home > Back-end >  is it possible to refer to a type when implementing a function with type parameters in typescript
is it possible to refer to a type when implementing a function with type parameters in typescript

Time:06-27

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?

CodePudding user response:

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

type MyFuncType = <T>() => void;
// instead of: type MyFuncType<T> = () => void;

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