type conversion - toString() in Typescript is suppose to work like this? -


i think typescript compiler should realize when type seen unit , use unit, when try following code shows me key words as, operators < classname > doesn't work expected or missing something? point of view typescript guarantee types when functions/constructors used explicitly:

typescript code:

class documents{     title: string;      tostring() {         return this.title;     } } class unit {      name: string = 'my name';     documents: documents[];      constructor(name:string, documents:documents[]) {         this.name = name;         this.documents = documents;     }      tostring() {         return this.name;     } }  let req = { name: 'unit 1', documents: [{ title: null }, { title: 'i have title' }, { title: null }] };  function cast<t>(param: t) {     let result: t = param;     return result; }  console.log('unit: ', cast<unit>(req).tostring()); console.log('docs: ', cast<unit>(req).documents[0].tostring()) console.log('now using unit directly'); console.log((req unit).tostring()) console.log((<unit>req).tostring())  console.log('converting unit manually') console.log(new unit(req.name, req.documents).tostring()); console.log(new unit(req.name, req.documents).documents[0].tostring()); 

and console result following:

unit:  [object object] (unknown) docs:  [object object] (unknown) using unit directly (unknown) [object object] (unknown) [object object] (unknown) converting unit manually (unknown) unit 1 (unknown) [object object] 

expected behavior:

unit:  unit 1 (unknown) docs:  title1 (unknown) using unit directly (unknown) unit 1 (unknown) unit 1 (unknown) converting unit manually (unknown) unit 1 (unknown) title 1 


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -