接口契约
TypeScript的核心原则之一是对值所具有的结构进行类型检查。它有时被称作“结构性子类型化”或“鸭式变型法”。
在TypeScript中,接口的作用就是为这些类命名和为你的代码或第三方代码定义契约。
实例如下:
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
上面的代码中,接口LabelledValue就像是一个契约,我们只会去关注传给printLabel
的值的外形。
还有一点值得提的是,类型检查器不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以。
接口可选属性
带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?
符号。
interface SquareConfig {
color?: string;
width?: number;
}
接口只读属性
一些对象属性只能在对象刚创建的时候修改其值。这时候可以在属性前面用readonly
来指定只读属性:
interface Point {
readonly x: number;
readonly y: number;
}
TypeScript具有ReadonlyArray<T>
类型,它与Array<T>
相似,只是把所有可变方法去掉了,因此可以确保数组创建后再也不能被修改.
readonly VS const
const
表示不可变的常量,
readonly
表示属性。
readonly
修饰的属性必须在声明时或构造函数里被初始化。
实现接口
与C#或Java里接口的基本作用一样,TypeScript也能够用它来明确的强制一个类去符合某种契约。
继承接口
和类一样,接口也可以相互继承。这让我们能够从一个接口里复制成员到另一个接口里,可以灵活的将接口分割到可重用的模块里。
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成员。(这意味这当接口继承了一个拥有private或protected成员的时候,这个接口类型只能被这个类或其子类所实现)
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
// Error: Property 'state' is missing in type 'Image'.
class Image implements SelectableControl {
select() { }
}