typescript - Shorthand for assigning variables -


when have code

interface foo1 {     a: string;     b: boolean     c: object; }  interface foo2 extends foo1 {     d: number; } 

can use shorthand assigning variables object created foo1 newly created object type foo2?

this little bit annoying, when have object 10 attributes...

var test1: foo1 = { a: '...', b: true, c: {} };  var test2: foo2 = { a: test1.a, b: test1.b, c: test1.c, d: 3 }; 

typescript allow cast item in case... although means test1 , test2 same object.

interface foo1 {     a: string;     b: boolean     c: object; }  interface foo2 extends foo1 {     d: number; }  var test1: foo1 = { a: '...', b: true, c: {} };  var test2: foo2 = <foo2> test1; test2.d = 1; 

if want copy, not same object, can create method copy object's properties. here example of copy:

var test1: foo1 = { a: '...', b: true, c: {} };  var test2: foo2 = <foo2>{}; (var variable in test1) {     if( test1.hasownproperty( variable ) ) {         test2[variable] = test1[variable];     } } 

with little hint of generics, can encapsulate in static helper method, this:

class objecthelper {     static copy<tfrom, tto>(from: tfrom) : tto {         var = <tto> {};         (var variable in from) {             if(from.hasownproperty(variable)) {                 to[variable] = from[variable];             }         }         return to;     } }  var test1: foo1 = { a: '...', b: true, c: {} }; var test2: foo2 = objecthelper.copy<foo1, foo2>(test1); 

Comments