Description
A common pattern in JavaScript libraries is to copy properties from a variable number of arguments onto the first argument. This is also the behavior of Object.assign
. A simple implementation of this pattern in TypeScript might look like this:
function assign(destination: any, ...sources: any[]): any {
sources.forEach(function (source) {
for (let key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
});
return destination;
}
This works fine, however with intersection types in 1.6 this could be better:
function assign<T, U>(destination: T, ...sources: U[]): T & U {
...
}
This works for one argument, but more than one fail because U
isn't actually the type needed for the intersection. What is needed (as suggested here) is a rest type parameter. It might look something similar to the following:
function assign<T, ...U>(destination: T, ...sources: U[]): T & U {
U
would be the intersection of all rest parameters passed to assign()
and the return value would expand to something like T & (U0 & ... UN)
. With the push for composable types and ES6 standardizing the above behavior (in Object.assign
) a syntax for generics like this would be very useful.