मैं thomaux से सहमत हूँ कि इनिशियलाइज़ेशन टाइप चेकिंग एरर एक टाइपस्क्रिप्ट बग है। हालाँकि, मैं अभी भी एकल स्टेटमेंट में सही प्रकार की जाँच के साथ डिक्लेयर की घोषणा करने और आरंभ करने का एक तरीका खोजना चाहता था। यह कार्यान्वयन लंबा है, हालांकि यह अतिरिक्त कार्यक्षमता जैसे कि ए containsKey(key: string)और remove(key: string)विधि जोड़ता है । मुझे संदेह है कि 0.9 रिलीज में जेनरिक उपलब्ध होने के बाद इसे सरल बनाया जा सकता है।
सबसे पहले हम आधार शब्दकोश वर्ग और इंटरफ़ेस की घोषणा करते हैं। अनुक्रमणिका के लिए इंटरफ़ेस आवश्यक है क्योंकि कक्षाएं उन्हें लागू नहीं कर सकती हैं।
interface IDictionary {
add(key: string, value: any): void;
remove(key: string): void;
containsKey(key: string): bool;
keys(): string[];
values(): any[];
}
class Dictionary {
_keys: string[] = new string[];
_values: any[] = new any[];
constructor(init: { key: string; value: any; }[]) {
for (var x = 0; x < init.length; x++) {
this[init[x].key] = init[x].value;
this._keys.push(init[x].key);
this._values.push(init[x].value);
}
}
add(key: string, value: any) {
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): any[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary {
return this;
}
}
अब हम व्यक्ति को विशिष्ट प्रकार और शब्दकोश / शब्दकोश इंटरफ़ेस घोषित करते हैं। पर्सनलाइड में ध्यान दें कि हम कैसे ओवरराइड करते हैं values()और toLookup()सही प्रकार वापस करते हैं।
interface IPerson {
firstName: string;
lastName: string;
}
interface IPersonDictionary extends IDictionary {
[index: string]: IPerson;
values(): IPerson[];
}
class PersonDictionary extends Dictionary {
constructor(init: { key: string; value: IPerson; }[]) {
super(init);
}
values(): IPerson[]{
return this._values;
}
toLookup(): IPersonDictionary {
return this;
}
}
और यहाँ एक सरल आरंभीकरण और उपयोग उदाहरण है:
var persons = new PersonDictionary([
{ key: "p1", value: { firstName: "F1", lastName: "L2" } },
{ key: "p2", value: { firstName: "F2", lastName: "L2" } },
{ key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();
alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2
persons.remove("p2");
if (!persons.containsKey("p2")) {
alert("Key no longer exists");
// alert: Key no longer exists
}
alert(persons.keys().join(", "));
// alert: p1, p3
Index signatures are incompatible.Type '{ firstName: string; }' is not assignable to type 'IPerson'.Property 'lastName' is missing in type '{ firstName: string; }'.