Interface in TypeScript -


i reading typescript handbook, in chapter of interface, found question:

interface labelledvalue {   label: string; }  function printlabel(labelledobj: labelledvalue) {   console.log(labelledobj.label); }  let myobj = {size: 10, label: "size 10 object"}; printlabel(myobj); 

the printlabel need object label:string property, object passed has property called size. ok cause compiler checks @ least ones required present , match types required.

but, call printlabel in way:

printlabel({size: 10, label: "size 10 object"}); 

the compile throws exception.

so why?

the documentation outdated , an issue exists fix it.

from what's new in typescript page:

typescript 1.6 enforces stricter object literal assignment checks purpose of catching excess or misspelled properties. specifically, when fresh object literal assigned variable or passed argument non-empty target type, error object literal specify properties don't exist in target type.

the idea it's common pattern pass in object literal bag of options. instance:

interface connectionoptions {     tryhttps?: boolean;     url?: string;     username?: string;     password?: string; } 

but of properties optional. before 1.6, misspell of them , compiler never catch error:

declare function connect(options: connectionoptions);  // notice property given 'tryhttps' instead of 'tryhttps'. connect({ url: "stackoverflow.com", tryhttps: true }); 

you can around adding type assertion type you're assigning to:

printlabel({size: 10, label: "size 10 object"} labelledvalue); // or... printlabel(<labelledvalue>{size: 10, label: "size 10 object"}); 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -