声明并初始化Typescript中的Dictionary


247

给出以下代码

interface IPerson {
   firstName: string;
   lastName: string;
}

var persons: { [id: string]: IPerson; } = {
   "p1": { firstName: "F1", lastName: "L1" },
   "p2": { firstName: "F2" }
};

为什么不拒绝初始化?毕竟,第二个对象没有“ lastName”属性。


11
注意:此问题已得到修复(不确定确切的TS版本)。正如您所料,我在VS中收到这些错误:Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.
Simon_Weaver 2015年

Answers:


289

编辑:此后已在最新的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

3
为什么需要id符号?似乎没有必要。
keewic

4
使用该id符号,可以声明字典键的类型。使用上面的声明,您不能执行以下操作:persons[1] = { firstName: 'F1', lastName: 'L1' }
thomaux

2
总是出于某种原因忘记此语法!
eddiewould '18

12
id符号可以命名为任何您喜欢的名称,其设计旨在使其更易于阅读代码。例如 { [username: string] : IPerson; }
Guy Park

1
@Robouste我将使用Lodash的findKey方法,或者,如果您希望使用本机解决方案,则可以基于Object.entries构建。如果您有兴趣获取完整的键列表,请查看Object.keys
thomaux

82

要在打字稿中使用字典对象,可以使用以下界面:

interface Dictionary<T> {
    [Key: string]: T;
}

并将其用于您的类属性类型。

export class SearchParameters {
    SearchFor: Dictionary<string> = {};
}

使用和初始化此类,

getUsers(): Observable<any> {
        var searchParams = new SearchParameters();
        searchParams.SearchFor['userId'] = '1';
        searchParams.SearchFor['userName'] = 'xyz';

        return this.http.post(searchParams, 'users/search')
            .map(res => {
                return res;
            })
            .catch(this.handleError.bind(this));
    }

60

我同意thomaux的观点,初始化类型检查错误是TypeScript错误。但是,我仍然想找到一种在正确的类型检查中声明和初始化Dictionary的方法。此实现较长,但是增加了诸如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;
    }
}

现在,我们声明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

非常有用的示例代码。“接口IDictionary”包含一个小的错字,因为引用了IPerson。
毫克

也会很好地实现元素计数
nurettin

@dmck该声明containsKey(key: string): bool;不适用于TypeScript 1.5.0-beta。应该更改为containsKey(key: string): boolean;
Amarjeet Singh

1
你为什么不delcare泛型?Dictionary <T>,则无需创建PersonDictionary类。您可以这样声明:var person = new Dictionary <IPerson>();
Benoit

我已经有效地使用了这样的通用词典。我在这里找到:fabiolandoni.ch/...
CAK2

5

这是受@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;
      }
    }


-1

现在,有一个库可以在打字稿中提供强类型的,可查询的集合

这些集合是:

  • 清单
  • 字典

该库称为ts-generic-collections-linq

GitHub上的源代码:

https://github.com/VeritasSoftware/ts-generic-collections

NPM:

https://www.npmjs.com/package/ts-generic-collections-linq

使用此库,您可以创建集合(如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();

找不到为此的npm包
哈利

1
@Harry-npm软件包称为“ ts-generic-collections-linq”
Ade
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.