Moddable-OpenSource / moddable

Tools for developers to create truly open IoT products using standard JavaScript on low cost microcontrollers.
http://www.moddable.com
1.34k stars 237 forks source link

Typings for Time.microseconds #1405

Closed cmidgley closed 1 month ago

cmidgley commented 2 months ago

Added microseconds to Time type definitions.

I spent too much time debating this implementation with myself! The simple solution is to add it as another property and leave it up to the user to decide if they wish to use it or not (without any TS-level validation, as in readonly microseconds: number). A more complex solution would be to create a separate .d.ts file that extends Time and change the manifest to include it for the platforms that implement microseconds. But that turns into an ugly build problem for consumers of it - for example, code using microseconds for ESP32 would fail to build on simulator requiring breaking apart source files and adjusting manifest files when otherwise you could have done a runtime check.

I ended up marking it optional (readonly microseconds?: number), which with TS strict on would require you to check it but without strict it will just allow the access. This seemed to most closely match how the JS implementation works, and allows the simple pattern of Time.microseconds ?? Time.ticks * 1000 if you wish to emulate it.

phoddie commented 2 months ago

All makes sense. We'll get this merged.

I guess TypeScript isn't really set-up to deal with patching to augment a class, at least not when that's done invisibly to TypeScript. Understandable.

An alternative would be to provide a default implementation of microseconds. The downside there is that there wouldn't be an easy way to detect whether the additional resolution is available.

mkellner commented 2 months ago

This has been merged and will be available in the next update.