basarat / basarat/typescript-book

"Best practice" way to extend type definitions (Mixin)

Open
#167 5 comments 3 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
21.6k
Forks
2.6k
PR merge metrics
No merged PRs in 30d

Description

I'm hoping to start a discussion on what is "best practice" when extending a type definition (d.ts).
A good example of where this is needed is with mixins. For example when using LoDash. The `LoDashStatic` definition doesn't contain your mixins obviously. So you somehow need to add them.

https://basarat.gitbooks.io/typescript/content/docs/project/globals.html
Gives a nice clean way to extend lib.d.ts. But I assume it's limited to lib.d.ts. It also states that the file should be named `globals.d.ts`.

https://basarat.gitbooks.io/typescript/content/docs/tips/jquery.html
Shows how to add your plugin to the jquery definition. It also states that the file should be named `jquery-.d.ts`.

So far so good.

Is the "best practice" way to define mixins to have a file called `lodash-mixins.d.ts`?
And the file should look like this:

```
interface LoDashStatic {
myMixin: Function;
}
```

But the only way I could get it to work was like this:

```
declare module _ {
interface LoDashStatic {
myMixin: Function;
}
}
```

Personally I like to keep the deceleration and implementation of a mixin together. But I couldn't figure out a way to get the implementation inside the `lodash-mixins.d.ts` file.

However if the file was renamed to `lodash-mixins.ts`, then I can do this:

```
declare module _ {
interface LoDashStatic {
myMixin: Function;
}
}

_.mixin({
myMixin: function () {}
});
```

Which is "clean" to me. But it goes against the jquery example :(

Is this a good or bad approach?

A completely different way is to define your own interfaces.

```
interface ILoDashWithMixins extends _.LoDashStatic {
myMixin: Function;
}
```

But I don't like this approach much.

Looking forward to hearing your opinions :)

Contributor guide

Open the contributing guide

Research direction

Start by comparing the linked globals.d.ts and jquery-.d.ts guidance with the proposed lodash-mixins.d.ts and lodash-mixins.ts examples. Done means reaching and documenting a clear recommendation for extending LoDashStatic and placing the mixin implementation.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.