Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 242
U Avalos Avatar asked Mar 14 '23 20:03

U Avalos


1 Answers

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..

like image 187
U Avalos Avatar answered May 04 '23 13:05

U Avalos