给定以下代码
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
为什么不拒绝初始化?毕竟,第二个对象没有“lastName”属性。
给定以下代码
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
为什么不拒绝初始化?毕竟,第二个对象没有“lastName”属性。
当前回答
Record<Tkey, Tobject>有点像c#字典
let myRecord: Record<string, number> = {};
//Add
myRecord[”key1”] = 1;
//Remove
delete myRecord[”key1"];
//Loop
for (var key in myRecord) {
var value = myRecord[key];
}
其他回答
下面是一个更通用的Dictionary实现,灵感来自@dmck
interface IDictionary<T> {
add(key: string, value: T): void;
remove(key: string): void;
containsKey(key: string): boolean;
keys(): string[];
values(): T[];
}
class Dictionary<T> implements IDictionary<T> {
_keys: string[] = [];
_values: T[] = [];
constructor(init?: { key: string; value: T; }[]) {
if (init) {
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: T) {
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(): T[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary<T> {
return this;
}
}
如果你正在寻找一个简单的方法来创建一个字典,即使在typescript中,它是使用Map对象。文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map的链接。Map对象主要有添加、检索、删除和删除所有元素的方法。
dictionary= new Map<string, string>();
dictionary.set("key", "value");
dictionary.get("key");
dictionary.delete("key");
dictionary.clear(); //Removes all key-value pairs
Record<Tkey, Tobject>有点像c#字典
let myRecord: Record<string, number> = {};
//Add
myRecord[”key1”] = 1;
//Remove
delete myRecord[”key1"];
//Loop
for (var key in myRecord) {
var value = myRecord[key];
}
如果你想忽略一个属性,通过添加一个问号将其标记为可选:
interface IPerson {
firstName: string;
lastName?: string;
}
编辑:这个问题已经在最新的TS版本中修复了。引用@Simon_Weaver对OP帖子的评论:
注意:这已经被修复(不确定确切的TS版本)。我 在VS中得到这些错误,正如你所期望的:索引签名是 不相容的。类型'{firstName:字符串;}'不能赋值给类型 “IPerson”。属性“lastName”在类型中缺失 字符串;}”。
显然,当在声明时传递初始数据时,这不起作用。 我猜这是TypeScript中的一个bug,所以你应该在项目站点上提出一个。
你可以通过在声明和初始化中分割你的例子来使用类型化字典,比如:
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error