My team is evaluating switching some of our files to TypeScript from JavaScript, and we make extensive use of some custom mixin methods in our code. From doing some basic tests, it seems that while we can use _.mixin to create mixins as per the norm, we cannot reference them without getting a compilation error. Of course, we could put these references in the definition file, but I usually prefer not to modify that.
Is there any way to do what we're looking for, or are we out of luck?
Consuming. From there you'll be able to use lodash in your TypeScript code with no fuss. This works for both modules and global code.
Mixins are a faux-multiple inheritance pattern for classes in JavaScript which TypeScript has support for. The pattern allows you to create a class which is a merge of many classes. To get started, we need a type which we'll use to extend other classes from.
A mixin class is a class that implements a distinct aspect of functionality. Other classes can then include the mixin and access its methods and properties. That way, mixins provide a form of code reuse that is based on composing behavior.
See TypeScript docs on extending built-in types, which I think applies here as well. _
is defined as var _: _.LoDashStatic
, and var
s are not currently extendable.
The best way that I found to expose extensions is via a lodash-mixins.ts
script that defines a new LoDashMixins
interface (extending LoDashStatic
), applies the mixins, and exports _
cast to the custom interface. This example defines a single mixin, but the idea is to add all your mixins to one script for easy importing.
import * as _ from 'lodash';
import xdiff from './xdiff';
interface LoDashMixins extends _.LoDashStatic {
xdiff<T>(array:T[], values:T[]): T[];
}
_.mixin({xdiff:xdiff});
export default <LoDashMixins>_;
When you want to use the mixins, import './lodash-mixins'
instead of 'lodash'
. You now have compile-time visibility to all of the built-in functions, as well as your mixins.
import _ from './lodash-mixins';
_.map([]); // built-in function still compiles
_.xdiff([], []); // mixin function compiles too
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With