泛型变量 / 类型变量
// 函数泛型注解
function identify<T>(arg: T): T {
return arg;
}
identify<number>(333);
// 实际 ts 是可以推断出来的
identify(333);
let a: <T>(arg: T) => T = identify;
// 也可以用对象字面量的方式来定义泛型类型
let a: {<T>(arg:T): T} = identify;
// 接口可以描述对象的形状,那么就可以抽离出一个interface
interface IIdentify {
<T>(arg: T): T
}
let a: IIdentify = identify;
泛型类
class CounterNum<T> {
initialNum: T;
add(x: T, y: T) => T;
}
let counterNum = new CounterNum<number>();
counterNum.initialNum = 0;
counterNum.add(x, y) => {return x + y;};
泛型约束
interface LengthWide {
length: number
}
// 在这里继承了 LengthWide 接口,下面的打印就不会报错了
function fn<T extends LengthWide> (arg: T): T {
console.log(arg.length); // 报错 如果没有约束泛型类型,就不存在length属性
return arg;
}
交叉类型
interface Sentence {
title: string;
content: string;
}
interface Url {
url: string;
}
class Music<T extends Sentence & Url> {
props: T;
constructor (arg: T) {
this.props = arg;
}
info (): T {
return {
url: this.props.url,
title: this.props.title,
content: this.props.content
}
}
}
元组 Tuple
元祖类型允许描述一个已知元素数量和类型的数组。
给元祖越界的时候,元素类型必须为联合类型。
let arr = [string, number];
arr = ["hello", 0]; // ok
arr = [0, "hello"]; // error
arr.push("world"); // ok
arr.push(false); // error boolean 不是( string | number )类型;
let arr1 = [string, number, boolean?]; // 可选元素类型
arr1 = ["a", 1, false]; // ok
arr1 = ["b", 2]; // ok
枚举
可以定义一些带有名字的常量。
也可以通过枚举的属性来访问枚举的成员,和枚举的名字来访问枚举类型。
enum Direction {
Up,
Down,
Left,
Right
}
// 当我们没有定义值时,默认是数字,且自增长
console.log(Direction.Up); // -> 0
console.log(Direction.Down); // -> 1
console.log(Direction.Left); // -> 2
console.log(Direction.Right);// -> 3
enum Direction {
Up = 1,
Down,
Left,
Right
}
// 当定义了第一个值且为数字时,后面的会依据第一个值自增长
console.log(Direction.Up); // -> 1
console.log(Direction.Down); // -> 2
console.log(Direction.Left); // -> 3
console.log(Direction.Right);// -> 4
enum Response {
No = 0,
Yes = 1
}
function response (msg: Response): void {
// ...
}
response(Response.Yes);