8

I have this method signature on a class:

lock(key: string, opts: any, cb?: LMClientLockCallBack): void;

if a user uses it like so:

lock('foo', null, (err,val) => {

});

they will get the right typings. However, if they omit the options argument and do this:

lock('foo', (err,val) => {

});

then tsc sees the callback function as type any, just like this:

enter image description here

Is there any way to allow users to avoid passing an empty object or null as the second argument, and shift the callback over?

I tried overloading the method, into two definitions:

  lock(key: string, cb: LMClientLockCallBack, n?: LMClientLockCallBack) : void;

  lock(key: string, opts: any, cb?: LMClientLockCallBack) { ... }

but it still doesn't compile, there are new problems:

enter image description here

and if I try this:

  lock(key: string, cb: LMClientLockCallBack) : void;

  lock(key: string, opts: any, cb?: LMClientLockCallBack) { ... }

I get this:

enter image description here

Surely there must be a solution to this one?

1 Answer 1

20

When overloading the method in TypeScript, the implementation doesn't count as one of overloads. You should thus create three function definitions: two ones for different overloads, as you've already done, and the third - with optional argument and real implementation, which is in your code erroneously connected to the second overload definition. So you'll have:

lock(key: string, cb: LMClientLockCallBack) : void;
lock(key: string, opts: any, cb: LMClientLockCallBack): void;

lock(key: string, opts: any, cb?: LMClientLockCallBack) { ... }

So, if the second argument is a callback - user will get the first overload typings, if it is anything else, but the third argument is a callback - the second overload typings. But in both cases they will call the same implementation, just like it would be in pure JavaScript.

Sign up to request clarification or add additional context in comments.

1 Comment

the implementation doesn't count as one of overloads. that single statement saved my day.....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.