[Typescript] Generics using TypeScript

In this lesson we cover the key reason why programming languages need generics. We then show how use them effectively with TypeScript. We show plenty of examples where generics prevent common programming mistakes.

class Query<T> { 
    protected items: T[];
    push(item:T) { this.items.push(item) }
    pop():T { return this.items.shift()} 
}

const q = new Query<number>();
q.push("1"); // compiler error
q.push(1);
const res = q.pop();
function reverse<T>(ary: T[]): T[] { 
    return ary.slice().reverse();
}

const ary = [{ name: "one" }, { name: "two" }];
const ary2 = [{ name2: "one" }, { name: "two" }];
const res = reverse<{name: string}>(ary);
const res2 = reverse<{name: string}>(ary2); // compile error for {name2: "one"}
res.push({ name2: "three" }); // compile error
原文地址:https://www.cnblogs.com/Answer1215/p/6729812.html