TypeScript笔记

#安装typescript [1]
npm install -g typescript

#编译typescript
tsc test.ts    //会生成test.js文件

#泛型,即使用“类型变量”,函数或者类申明时后面 < > 尖括号中的变量即是类型变量。 [1]
function identity<T>(arg: T): T {
    return arg;
}
console.log( identity<number>(5) );

#类型推论,编译器会根据传入的参数自动地帮助我们确定T的类型:
let output = identity("myString");  // type of output will be 'string'

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

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

#泛型约束,尖括号中使用了extends
interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);  // Now we know it has a .length property, so no more error
    return arg;
}

loggingIdentity(3);                     // Error, number doesn't have a .length property
loggingIdentity({length: 10, value: 3});//需要传入符合约束类型的值,必须包含必须的属性

posted on 2017-09-27 23:20  dream_bccb  阅读(116)  评论(0)    收藏  举报