TypeScript笔记[5]泛型+Dictionary 转

TypeScript笔记[5]泛型

 

在C++、C#、Java等主流编程语言中,一般对泛型编程提供了支持。合理利用泛型,可以提高开发效率、提升代码质量。

例如在C++编程语言中,常常利用下面的结构表示一个链表的结点:

template<typename T>
struct Node
{
    T data;
    Node *next;
};

在TS中,也提供了泛型的支持。下面介绍一下TS中的泛型函数与泛型类。

一、泛型函数

function Func<T>(a: T): T {
    return a;
}

上面的代码中,<T>表示一个预设的类型,当Func<T>接受一个具体的参数时,会根据参数的类型产生对应版本的函数。例如,在Func(1)中Func<T>会作为:

function Func(a: number): number {
    return a;
}

而在Func("魏晋风度")中Func<T>会作为:

function Func(a: string): string {
    return a;
}

二、泛型类型

变量的类型也可以是泛型的:

function identity<T>(arg: T): T {
    return arg;
}

var myIdentity: <U>(arg: U) => U = identity;

三、泛型类

泛型函数将<T>放在函数名之后,泛型类的<T>也放在类型之后。我们来看一个来自官网的例子:

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

var myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

这个例子中,用number将一个泛型类实例化。

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;
    }
}
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();

 

posted @ 2015-12-18 10:28  NNiiccoo  阅读(800)  评论(0编辑  收藏  举报

去Yes