2015-11-03 3 views
41

वहाँ क्या टाइपप्रति कल्पना एक प्रकार अभिकथन कॉल के बीच कोई अंतर है:प्रकार सम्मिलन और टाइपस्क्रिप्ट में नए 'as` ऑपरेटर के बीच कोई अंतर?

var circle = <Circle> createShape("circle"); 

और neweras ऑपरेटर:

var circle = createShape("circle") as Circle; 

दोनों जिनमें से आम तौर पर संकलन समय कास्टिंग के लिए उपयोग किया जाता है?

उत्तर

48

अंतर यह है कि as Circle टीएसएक्स फ़ाइलों में काम करता है, लेकिन <Circle> जेएसएक्स सिंटैक्स के साथ संघर्ष करता है। इस कारण से as पेश किया गया था।

उदाहरण के लिए

, एक .tsx फ़ाइल में निम्न कोड:

var circle = <Circle> createShape("circle"); 

निम्न त्रुटि में परिणाम होगा:

error TS17002: Expected corresponding JSX closing tag for 'Circle'.

हालांकि, as Circle ठीक काम करेंगे।

अब से as Circle का उपयोग करें। यह अनुशंसित वाक्यविन्यास है।

13

Wiki page से: "क्या टाइपप्रति में [1.6] नया क्या है":

New .tsx file extension and as operator

TypeScript 1.6 introduces a new .tsx file extension. This extension does two things: it enables JSX inside of TypeScript files, and it makes the new as operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator). For example:

var x = <any> foo; 
// is equivalent to: 
var x = foo as any; 
संबंधित मुद्दे