zoukankan      html  css  js  c++  java
  • TypeScript的Dictionary的写法

    TypeScript中做类似ActionScript中的Dictionary功能时的写法

    var dict: { [index: string]: Function[]; } = {};
    dict['Matt'] = []; // ok
    dict['Chris'] ="123"; //编译警告
    dict[1] =  []; //编译警告

    还有一种方法就是使用typescript-collections 里面的Dictionary类

    https://github.com/basarat/typescript-collections#a-sample-on-dictionary

    用法是这样的。

    class Person {
        constructor(public name: string, public yearOfBirth: number,public city?:string) {
        }
        toString() {
            return this.name + "-" + this.yearOfBirth; // City is not a part of the key. 
        }
    }
    
    class Car {
        constructor(public company: string, public type: string, public year: number) {
        }
        toString() {
            // Short hand. Adds each own property 
            return collections.toString(this);
        }
    }
    var dict = new collections.Dictionary<Person, Car>();
    dict.setValue(new Person("john", 1970,"melbourne"), new Car("honda", "city", 2002));
    dict.setValue(new Person("gavin", 1984), new Car("ferrari", "F50", 2006));
    console.log("Orig");
    console.log(dict);
    
    // Changes the same john, since city is not part of key 
    dict.setValue(new Person("john", 1970, "sydney"), new Car("honda", "accord", 2006)); 
    // Add a new john
    dict.setValue(new Person("john", 1971), new Car("nissan", "micra", 2010)); 
    console.log("Updated");
    console.log(dict);
    
    // Showing getting / setting a single car: 
    console.log("Single Item");
    var person = new Person("john", 1970); 
    console.log("-Person:");
    console.log(person);
    
    var car = dict.getValue(person);
    console.log("-Car:");
    console.log(car.toString());
  • 相关阅读:
    arm单板上移植gdb
    video on web
    chromium源码阅读
    CE-HTML简介
    multi-tap
    DPDK 网卡RSS(receive side scaling)简介
    c语言实现带LRU机制的哈希表
    Linux TCP协议使用的变量
    scp源码浅析
    Linux e1000e网卡驱动
  • 原文地址:https://www.cnblogs.com/longhuang/p/3645555.html
Copyright © 2011-2022 走看看