Home > OS >  Types with different parameters like function overload
Types with different parameters like function overload

Time:03-23

I'm trying to write a type which acts as a function signature that allows to have to different set of parameters:

  • The first case, the function expects a predicate.
  • The second case, the function expects two parameters.

This is the example: enter image description here

I'm pretty sure this can be done because we have the function overload, but I've been able to use them only inside a class. But it's basically the same thing, expect in this case I'm defining the method as a global variable.

CodePudding user response:

Use an interface to describe a set of call signatures:

interface TCommon<TEntity> {
    (predicate: ((entity: TEntity) => TEntity | void)): void
    (propertyName: keyof TEntity, newValue: unknown): void;
}

But we aren't quite done yet. The second parameter is optional in the sense that the first overload doesn't need a second parameter but the second overload does.

So we mark the second parameter as optional:

const method: TCommon<IEntity> = (param1, param2?: unknown) => {

And that's it.

Playground

  • Related