Signature for Object.assign in typescript?

What is the correct signature for Object.assign in typescript? We implemented a #extend function similar to jQuery (similar to Object.assign). Unfortunately, the compiler does not recognize the extended object.

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

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

 data.foo //compiler error
+4
source share
2 answers

According to https://github.com/Microsoft/TypeScript/blob/master/src/lib/es6.d.ts , this is an announcement 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 will 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, the question is whether to use this instead of the custom #extend ..

+5
source

You can also use casting:

(<any>Object).assign(this.success, success.json())
+2
source

Source: https://habr.com/ru/post/1621186/


All Articles