sinonjs / fake-timers

Fake setTimeout and friends (collectively known as "timers"). Useful in your JavaScript tests. Extracted from Sinon.JS
BSD 3-Clause "New" or "Revised" License
797 stars 104 forks source link

TypeScript types for install config are too strict. #382

Closed peterjuras closed 3 years ago

peterjuras commented 3 years ago

What did you expect to happen?

The FakeTimers.install method should be usable with a partial config object, i.e. only specifying now and using the default values for other configuration properties. In the newest TypeScript version it appears that a full object needs to be passed when using the install method.

The generated Config type appears to have all properties marked as non-optional. This appears to be similar to the already fixed issue #352.

What actually happens

Calling install in the following way:

import FakeTimers from "@sinonjs/fake-timers";

FakeTimers.install({ now: 1 });

Leads to the following TypeScript error:

Argument of type '{ now: number; }' is not assignable to parameter of type 'Config'.
Type '{ now: number; }' is missing the following properties from type 'Config': toFake, loopLimit, shouldAdvanceTime, advanceTimeDeltats(2345)

How to reproduce

You can find an example in this Codesandbox

fatso83 commented 3 years ago

Hi, it seems the Config object should have optionals everywhere. Not sure why that wasn't done to begin with. AFAIK, all of the props in https://github.com/henhal/fake-timers/blob/cdd0391fa39391f102bafc7678df9d060386253f/src/fake-timers-src.js#L45 should have [] added to make them optional.

- * @property {number|Date} now a number (in milliseconds) or a Date object (default epoch)
+ * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)

That seems fixable :)

fatso83 commented 3 years ago

Yup, just made a test

$ npx tsc index.ts
index.ts:3:20 - error TS2345: Argument of type '{ now: number; }' is not assignable to parameter of type 'Config'.
  Type '{ now: number; }' is missing the following properties from type 'Config': toFake, loopLimit, shouldAdvanceTime, advanceTimeDelta

3 FakeTimers.install({ now: 1 });
                     ~~~~~~~~~~

Found 1 error.

# adding the brackets in my local fake-timers
$ npx tsc index.ts 

$ echo success!
fatso83 commented 3 years ago

This will be released as part of a new minor version in a few minutes.