对象类型:
TypeScript的核心原则之一是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。 在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。
interface LabelledValue {label: string;}function printLabel(labelledObj: LabelledValue) {console.log(labelledObj.label);}let myObj = {size: 10, label: "Size 10 Object"};printLabel(myObj);
// 带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?符号。interface SquareConfig {color?: string;width?: number;}function createSquare(config: SquareConfig): {color: string; area: number} {let newSquare = {color: "white", area: 100};if (config.color) {newSquare.color = config.color;}if (config.width) {newSquare.area = config.width * config.width;}return newSquare;}let mySquare = createSquare({color: "black"});
// 一些对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 readonly来指定只读属性:interface Point {readonly x: number;readonly y: number;}let p1: Point = { x: 10, y: 20 };p1.x = 5; // error!
// TypeScript具有ReadonlyArray<T>类型,它与Array<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!
函数类型:
为了使用接口表示函数类型,我们需要给接口定义一个调用签名。 它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。
interface SearchFunc {(source: string, subString: string): boolean;}
这样定义后,我们可以像使用其它接口一样使用这个函数类型的接口。
let mySearch: SearchFunc;mySearch = function(source: string, subString: string) {let result = source.search(subString);return result > -1;}
可索引类型:
与使用接口描述函数类型差不多,我们也可以描述那些能够“通过索引得到”的类型,比如a[10]或ageMap[“daniel”]。 可索引类型具有一个索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。
// 定义了StringArray接口,它具有索引签名。// 这个索引签名表示了当用number去索引StringArray时会得到string类型的返回值。interface StringArray {[index: number]: string;}let myArray: StringArray;myArray = ["Bob", "Fred"];let myStr: string = myArray[0];
类类型:
接口描述了类的公共部分,而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员。
interface ClockInterface {currentTime: Date;}class Clock implements ClockInterface {currentTime: Date;constructor(h: number, m: number) { }}

