接口
在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。
基本使用
//可选属性 可以对可能存在的属性进行预定义
interface SquareConfig {
color?: string;
width?: number;
}
let mySquare = createSquare({color: "black"}); //如果不使用可选属性会报错 缺少width
//只读属性 一些对象属性只能在对象刚刚创建的时候修改其值。
interface Point {
readonly x: number;
readonly y: number;
}
//ReadonlyArray<T>
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!
a = ro as number[]; //可以用类型断言重写:
//额外的属性检查
//索引签名
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
//SquareConfig可以有任意数量的属性,并且只要它们不是color和width,那么就无所谓它们的类型是什么。
//可索引的类型
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
//在函数中使用
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
//对于函数类型的类型检查来说,函数的参数名不需要与接口里定义的名字相匹配。
let mySearch: SearchFunc;
mySearch = function(src: string, sub: string): boolean {
let result = src.search(sub);
return result > -1;
}
//在类中使用
//TypeScript也能够用接口来明确的强制一个类去符合某种契约。
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
用const还是readonly?
做为变量使用的话用 const,若做为属性则使用readonly。
接口继承
//接口继承接口
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
//接口继承类
//当接口继承了一个类类型时,它会继承类的成员但不包括其实现。
//就好像接口声明了所有类中存在的成员,但并没有提供具体实现一样。
//接口同样会继承到类的private和protected成员。
//这意味着当你创建了一个接口继承了一个拥有私有或受保护的成员的类时,这个接口类型只能被这个类或其子类所实现(implement)。
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
//Button不具有s
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
// 错误:“Image”类型缺少“state”属性。
class Image implements SelectableControl {
select() { }
}
class Location {
}