Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lodash.mixin in TypeScript

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?

like image 888
Smartboy Avatar asked Feb 25 '15 17:02

Smartboy


People also ask

Can I use Lodash with TypeScript?

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.

What is mixin in TypeScript?

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.

What are Mixins in TypeScript 2.2 Mcq?

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.


1 Answers

See TypeScript docs on extending built-in types, which I think applies here as well. _ is defined as var _: _.LoDashStatic, and vars 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
like image 164
Chris Avatar answered Sep 29 '22 03:09

Chris