typescript(二)
1. 接口
1. 接口约束对象
接口可以约束对象的属性和其对应的类型。
interface Rectangle {
readonly width: number,//该属性必须存在,且只读,不能被赋值
height?: number,// 该属性可有可无
[x: string]: any //对象的属性不确定个数
}
let myRec: Rectangle = {
width: 10,
age: 10,
gender: ‘female‘
}2. 接口约束数组
相当于对象的特殊形式。
interface MyArray{
[x: number]: any
}
let arr: MyArray = [1,2];3. 接口约束类的方法实现
接口中的方法都是抽象方法。类实现接口的时候,要将接口中的方法全部实现。
1. 一个类可以实现多个接口
interface Animal {
eat(): void;
run(): void;
}
interface Person{
speak(): void;
}
class Tom implements Animal,Person {
eat() { }
run() { }
speak(){ }
}2. 接口可以继承;类实现继承的接口时,要实现接口和接口继承的抽象方法。
interface Animal {
eat(): void;
run(): void;
}
interface Bird extends Animal{
fly():void;
}
// 要实现接口本身的抽象方法,还要实现继承的抽象方法
class Tommy implements Bird {
eat() {}
run() {}
fly(){}
}4. 接口约束类(构造函数)的参数和静态方法
interface UserInterface {
new(name: string): User; // 指定构造函数必须传参
age: number //类上的属性,即静态属性
}
class User {
constructor(public name: string){} //public也可以不存在
static age = 10;
/*
使用public后,相当于
name: string;
constructor(name: string) {
this.name: name;
}
*/
}
function generateInstance(targetClass: UserInterface, name: string) {
return new targetClass(name);
}
generateInstance(User, ‘lyra‘);
console.log(generateInstance(User, ‘lyra‘))5. 接口约束函数
1. 约束函数表达式的变量
interface DiscountInterface {
(price:number):number
}
let discount:DiscountInterface = function(price: number):number {
return price*0.8
}当参数个数不确定时
interface SumInterface{
(...args:Array<number>): number
}
let sum = function(...args: number[]):number {
return args.reduce((a,b) => a+b , 0);
}2. 泛型
泛型指的时当声明函数,接口或者类时,不预先指定具体的类型,到调用的时候再指定的特性。
function createArray<T>(length: number, value: T): T[] {
let result: Array<T> = [];
for(let i=0; i<length; i++) {
result[i] = value;
}
return result;
}
createArray<number>(3, 3); // [3,3,3]
createArray<string>(3, ‘x‘); // [‘x‘, ‘x‘, ‘x‘]