TypeScript 素描 - 泛型、枚举

时间:2023-03-09 18:31:07
TypeScript 素描 - 泛型、枚举
/*
泛型,好处多多的功能.不过这里最基本的就不打算说了,仅准备说一些
和C#不同的地方
*/ /*
泛型接口
GenericIdentityFn 定义了方法的描述等
identity方法则是它的实现
myIdentntiy使用了GenericIdentityFn的规则而实现是identity
*/
interface GenericIdentityFn {
<T>(arg: T): T;
} function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn = identity; /*
泛型约束,虽然是泛型但是也不能胡来.做好约束也是非常重要的
而TypeScript的泛型约束也很有趣
*/ //接口
interface Lenthwise {
length: number;
}
//约束参数必须有length属性
function fun11<T extends Lenthwise>(arg: T) {
//可以放心的使用length了
arg.length;
}
/*
约束参数必须是类类型的,这里需要注意的,传进来的类需要是没有手
动指定构造函数的类,不过也可以这么定 new (x: string, y: number):
当然也有更高级的方法 比如指定类中的Prototype
*/
function fun12<T>(arg: { new (): T; }): T {
return new arg();
} fun12(Employee).fullName; /*
枚举,嗯 又是一个实用的东西
数字部分默认从0开始,当然如果指定了的话就是按照指定的值
*/
enum OrderType {
PayOk = 1,
NoPay = 2,
//因为上一个是2,所以这个是3
xxxx
}