给出以下代码
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
为什么不初始化被拒绝?毕竟,第二个对象没有“lastName”属性。
答案 0 :(得分:217)
编辑:此版本已在最新的TS版本中修复。引用@ Simon_Weaver对OP帖子的评论:
注意:此后已经修复(不确定哪个TS版本)。一世 如您所料,在VS中获取这些错误:
Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.
<小时/> 显然,在声明时传递初始数据时,这不起作用。 我想这是TypeScript中的一个错误,所以你应该在项目站点提出一个错误。
您可以通过在声明和初始化中拆分示例来使用键入的字典,例如:
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error
答案 1 :(得分:56)
我同意thomaux初始化类型检查错误是TypeScript错误。但是,我仍然希望找到一种方法,在单个语句中使用正确的类型检查来声明和初始化Dictionary。此实现时间较长,但它添加了其他功能,例如containsKey(key: string)
和remove(key: string)
方法。我怀疑,一旦0.9版本中提供了泛型,这可以简化。
首先我们声明基本的Dictionary类和接口。索引器需要该接口,因为类无法实现它们。
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;
}
}
现在我们声明Person特定类型和Dictionary / Dictionary接口。在PersonDictionary中注意我们如何覆盖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
答案 2 :(得分:49)
要在打字稿中使用字典对象,您可以使用如下界面:
[]
,并将其用于您的类属性类型。
interface Dictionary<T> {
[Key: string]: T;
}
使用并初始化此类,
export class SearchParameters {
SearchFor: Dictionary<string> = {};
}
答案 3 :(得分:7)
在您的情况下,Typescript失败,因为它希望所有字段都存在。使用 Record and Partial 实用程序类型来解决它。
Record<string, Partial<IPerson>>
interface IPerson {
firstName: string;
lastName: string;
}
var persons: Record<string, Partial<IPerson>> = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
说明。
备用。
如果您希望姓氏是可选的,可以附加一个? Typescript知道它是可选的。
lastName?: string;
https://www.typescriptlang.org/docs/handbook/utility-types.html
答案 4 :(得分:3)
如果要忽略属性,请通过添加问号将其标记为可选:
interface IPerson {
firstName: string;
lastName?: string;
}
答案 5 :(得分:1)
这是来自@dmck的更通用的Dictionary实现
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;
}
}
答案 6 :(得分:0)
现在,有一个库可以在打字稿中提供强类型的可查询集合。
集合是:
该库称为 ts-generic-collections 。
GitHub上的源代码:
https://github.com/VeritasSoftware/ts-generic-collections
使用此库,您可以创建集合(如List<T>
)并按如下所示查询它们。
let owners = new List<Owner>();
let owner = new Owner();
owner.id = 1;
owner.name = "John Doe";
owners.add(owner);
owner = new Owner();
owner.id = 2;
owner.name = "Jane Doe";
owners.add(owner);
let pets = new List<Pet>();
let pet = new Pet();
pet.ownerId = 2;
pet.name = "Sam";
pet.sex = Sex.M;
pets.add(pet);
pet = new Pet();
pet.ownerId = 1;
pet.name = "Jenny";
pet.sex = Sex.F;
pets.add(pet);
//query to get owners by the sex/gender of their pets
let ownersByPetSex = owners.join(pets, owner => owner.id, pet => pet.ownerId, (x, y) => new OwnerPet(x,y))
.groupBy(x => [x.pet.sex])
.select(x => new OwnersByPetSex(x.groups[0], x.list.select(x => x.owner)));
expect(ownersByPetSex.toArray().length === 2).toBeTruthy();
expect(ownersByPetSex.toArray()[0].sex == Sex.F).toBeTruthy();
expect(ownersByPetSex.toArray()[0].owners.length === 1).toBeTruthy();
expect(ownersByPetSex.toArray()[0].owners.toArray()[0].name == "John Doe").toBeTruthy();
expect(ownersByPetSex.toArray()[1].sex == Sex.M).toBeTruthy();
expect(ownersByPetSex.toArray()[1].owners.length == 1).toBeTruthy();
expect(ownersByPetSex.toArray()[1].owners.toArray()[0].name == "Jane Doe").toBeTruthy();