typescript1.7

Signature for Object.assign in typescript?


What's the correct signature for Object.assign in typescript? We've implemented a jquery-like #extend function (similar to Object.assign). Unfortunately, the compiler doesn't recognize the extended object.

 function extend<T>(dst : Object, ...src : Object[]) : T { //... }

 const data = extend({}, {foo: 'foo'});

 data.foo //compiler error

Solution

  • As per https://github.com/Microsoft/TypeScript/blob/master/src/lib/es6.d.ts, this is the declaration for Object.assign:

     assign<T, U>(target: T, source: U): T & U;
     assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
     assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
     assign(target: any, ...sources: any[]): any;
    

    So the implementation for #extend would look something like this:

     function extend<T, U>(target: T, source: U): T & U;
     function extend<T, U, V>(target: T, source1: U, source2: V): T & U & V;
     function extend<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
     function extend(target: any, ...sources: any[]): any {
        //implementation
     }
    

    However if es6.d.ts exists, then that begs the question of whether or not we should be using that instead of a custom #extend..