Search code examples
typescript

Generic function type validation


Is there a way, particularly as part of the function definition, for us to enforce a type constraint on the function definition?

For instance:

type IMyFunc<P = any,R = any> = (p: P) => R;

function myFunc<P = any, R = any>(p: P):R { ... }

How can we have the Typescript compiler validate that myFunc is an implementation of the interface IMyFunc?

One way I've found would be to use a separate declaration to validate this...

const f: IMyFunc = myFunc;

However, in this case the generic type parameters default to any (So you can't export and use f except in the default case). I suppose it is better than nothing, but I'd prefer something more succinct if it exists - preferably something that I can supply as part of the definition of myFunc.

For instance, it would be nice if you could do this:

function myFunc<P = any, R = any>(params: P):R {
  ...
} : IMyFunc<P,R>;

Solution

  • There is currently no way to annotate a function statement so that its call signature conforms to an existing function type. There's a longstanding open feature request at microsoft/TypeScript#22063 for that. If you want to see it happen, it wouldn't hurt for you to give it a 👍. It probably also wouldn't help very much, since even very highly upvoted feature requests don't always get implemented.

    Until or unless something changes, then, you'll need to do such checking a different way. You could do what you did with const f: IMyFunc = myFunc;, or even just define const myFunc: IMyFunc = function (p) { ⋯ }.