Looking at the TypeScript docs and trying out examples for Intersection Types and Mixins in TypeScript using the utility methods provided, I'm seeing essentially identical behavior and outcome from both methodologies. I'm ending up with an object in the end that is a combination of 1..n other types
, Interfaces
, or Classes
. Here are the methods I used in my coding samples and are stright from the TypeScript docs.
This is used to apply mixins
in TypeScript:
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
});
});
}
This is what I used for the intersection type
:
function extend<First, Second>(first: First, second: Second): First & Second {
const result: Partial<First & Second> = {};
for (const prop in first) {
if (first.hasOwnProperty(prop)) {
(<First>result)[prop] = first[prop];
}
}
for (const prop in second) {
if (second.hasOwnProperty(prop)) {
(<Second>result)[prop] = second[prop];
}
}
return <First & Second>result;
}
Aside from the fact that the mixins
method takes an array, and the intersection type
method specifically takes 2 values, they in the end from a behavior standpoint act identically. If I have a Person
and User
class each with separate properties and methods, after using either method above, I have the ability to create a new instance from either the type defined from the intersection type
or mixin
and see the combination of everything from both Person
and User
.
Ironically this is exactly what I want, but I feel I'm missing a purpose of when to use either. I did some digging and found this post related to JavaScript (
What's the difference between mixin() and extend() in Javascript libraries) but I'm not sure if extend
in this case is identical to an intersection type
in TypeScript (even though the helper method is called just that).
Looking at both helper methods they appear to copy or define properites from A to B exactly as desired. Can someone please explain the difference between the 2 in TypeScript and why one method would be used over the other?