Becklyn / mojave

A library of commonly used JavaScript tools and helpers by Becklyn
BSD 3-Clause "New" or "Revised" License
5 stars 3 forks source link

Use generic type parameter instead of very broad/„generic” return types #180

Closed keichinger closed 5 years ago

keichinger commented 5 years ago

Most mojave APIs are very generic by-design, which can lead to many situations where you have to cast the return of a mojave method to a more explicit/specific type, which is just unnecessary noise.

// before
let divElement = findOne(".my-div", this.container);
let inputElement = findOne(".my-input", this.container) as HTMLInputElement;

// after
let divElement = findOne(".my-div", this.container);
let inputElement = findOne<HTMLInputElement>(".my-input", this.container);

I've used the previously hardcoded types as default for the generic type parameters, which makes this change backwards compatible and allows us to omit the type parameters when they match the default.

This is the very first pass of making most methods generic and easier to work with. For extend, merge and debounce I found the following article pretty helpful: https://spin.atomicobject.com/2018/05/14/type-safe-object-merging-2-8/ However, it lacks support for variadic parameters, which we currently need for all methods. So we'll probably have to wait until https://github.com/Microsoft/TypeScript/issues/5453 has been merged.