Declare and initialize a Dictionary in Typescript

前端 未结 6 1067
闹比i
闹比i 2020-12-02 04:22

Given the following code

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

var persons: { [id: string]: IPerson; } = {
   \"p1\": { firstName         


        
6条回答
  •  日久生厌
    2020-12-02 04:42

    Here is a more general Dictionary implementation inspired by this from @dmck

        interface IDictionary {
          add(key: string, value: T): void;
          remove(key: string): void;
          containsKey(key: string): boolean;
          keys(): string[];
          values(): T[];
        }
    
        class Dictionary implements IDictionary {
    
          _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 {
            return this;
          }
        }
    

提交回复
热议问题