Definitelytyped: Sinon types are broken with overloads

Created on 25 Jun 2019  路  5Comments  路  Source: DefinitelyTyped/DefinitelyTyped

This was mentioned a little in https://github.com/DefinitelyTyped/DefinitelyTyped/pull/31606 but there isn't an open issue describing it. That PR broke stubbing overloaded methods:

class Bar {
    public foo(a: string): void;
    public foo(a: number): void;
    public foo(a: string | number): void {};
}

const bar = new Bar();
const barStub = sinon.stub(bar, "foo");

// This line gives an error:
// Argument of type '"test"' is not assignable to parameter of type 'number | SinonMatcher'.
barStub.withArgs("test"); 

I don't know if it's possible to fix this without just changing back to any, but it does seem like this should work.

Most helpful comment

+1 - This is _really_ annoying.

All 5 comments

+1 - This is _really_ annoying.

any news on this ?

Perhaps I should've posted this question in this thread:

Incidentally, it seems I am able to work around this problem in my particular case with good ol' @ts-ignore in my test case:

    const userStub = sinon.stub(User, 'findOne');

    // avoid TS2554: Expected 3-4 arguments, but got 1.
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    userStub.withArgs({ firebaseUid: userFirebaseUid }).resolves(user);

somehow totally didn't see this issue!

it will indeed be because the inferred types are not a combination of all the overloads but rather just one of them.

ultimately the solution is to specify the generics rather than inferring them, i think. but ill have a look in case we can just introduce a looser type for these cases.

also i dont think the pr you have all suspected is the one that broke it. your example code doesn't touch that interface. it is in fact the stub(obj, method) inference we added some time ago.

ok so the best i can come up with is that you'd have to specify your type arguments:

const barStub = stub<Bar, 'foo', [string]>(bar, 'foo');

If i modify the stub interface, the above will work (it won't at the min). Unfortunately you have to specify the initial two types as the following ones depend on them.

if this is better for you than what we have now, let me know and ill get a pr up

Was this page helpful?
0 / 5 - 0 ratings