यदि आप एक इंटरफेस की तरह है:
interface ISimpleObject {
foo: string;
bar?: any;
}
इस इंटरफ़ेस केवल कोड-हिंट/IntelliSense के लिए संकलन समय पर प्रयोग किया जाता है। इंटरफ़ेस का उपयोग किसी ऑब्जेक्ट को एक निश्चित तरीके से परिभाषित हस्ताक्षर के साथ करने का कठोर और प्रकार-सुरक्षित तरीका प्रदान करने के लिए किया जाता है।
आप एक समारोह का उपयोग कर interface
ऊपर परिभाषित है: यदि एक वस्तु ISimpleObject
इंटरफ़ेस का सही हस्ताक्षर नहीं है
function start(config: ISimpleObject):void {
}
टाइपप्रति संकलन विफल हो जाएगा।
// matches the interface as there is a foo property
start({foo: 'hello'});
// Type assertion -- intellisense will "know" that this is an ISimpleObject
// but it's not necessary as shown above to assert the type
var x = <ISimpleObject> { foo: 'hello' };
start(x);
// the type was inferred by declaration of variable type
var x : ISimpleObject = { foo: 'hello' };
start(x);
// the signature matches ... intellisense won't treat the variable x
// as anything but an object with a property of foo.
var x = { foo: 'hello' };
start(x);
// and a class option:
class Simple implements ISimpleObject {
constructor (public foo: string, public bar?: any) {
// automatically creates properties for foo and bar
}
}
start(new Simple("hello"));
किसी भी समय हस्ताक्षर से मेल नहीं खाता, संकलन विफल हो जाएगा:
// compile fail
var bad = { foobar: 'bad' };
start(bad);
// compile fail
var bad: ISimpleObject = { foobar: 'bad' };
// and so on.
कोई "सही" तरीका नहीं है
समारोह start
फोन करने के लिए कई वैध तकनीक रहे हैं इसे करने के लिए। यह शैली पसंद का मामला है।यदि यह एक उद्देश्य यह है कि निर्माण किया गया था (बजाय बस सीधे एक पैरामीटर के रूप में पारित) थे, मैं सामान्य रूप से प्रकार की घोषणा करेंगे:
var config: ISimpleObject = { foo: 'hello' };
इस तरह कोड: पूर्ण करने/IntelliSense कहीं भी काम करेंगे मैं config
चर प्रयोग किया है:
config.bar = { extra: '2014' };
टाइपस्क्रिप्ट में कोई "कास्टिंग" नहीं है। इसे एक प्रकार का दावा कहा जाता है और यहां वर्णित मामलों में इसकी आवश्यकता नहीं होनी चाहिए (मैंने ऊपर एक उदाहरण शामिल किया था जहां इसका उपयोग किया जा सकता था)। परिवर्तनीय प्रकार घोषित करने की कोई आवश्यकता नहीं है और फिर इस मामले में एक दावा का उपयोग करें (जैसा कि प्रकार पहले से ज्ञात था)।
मेरी इच्छा है कि मेरे पास और अधिक उत्थान हो! – mentat