C753E2B3-ACFE-4097-9B09-9660C026079D.png

对象类型:
TypeScript的核心原则之一是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。 在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

  1. interface LabelledValue {
  2. label: string;
  3. }
  4. function printLabel(labelledObj: LabelledValue) {
  5. console.log(labelledObj.label);
  6. }
  7. let myObj = {size: 10, label: "Size 10 Object"};
  8. printLabel(myObj);
  1. // 带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?符号。
  2. interface SquareConfig {
  3. color?: string;
  4. width?: number;
  5. }
  6. function createSquare(config: SquareConfig): {color: string; area: number} {
  7. let newSquare = {color: "white", area: 100};
  8. if (config.color) {
  9. newSquare.color = config.color;
  10. }
  11. if (config.width) {
  12. newSquare.area = config.width * config.width;
  13. }
  14. return newSquare;
  15. }
  16. let mySquare = createSquare({color: "black"});
  1. // 一些对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 readonly来指定只读属性:
  2. interface Point {
  3. readonly x: number;
  4. readonly y: number;
  5. }
  6. let p1: Point = { x: 10, y: 20 };
  7. p1.x = 5; // error!
  1. // TypeScript具有ReadonlyArray<T>类型,它与Array<T>相似,只是把所有可变方法去掉了,因此可以确保数组创建后再也不能被修改:
  2. let a: number[] = [1, 2, 3, 4];
  3. let ro: ReadonlyArray<number> = a;
  4. ro[0] = 12; // error!
  5. ro.push(5); // error!
  6. ro.length = 100; // error!
  7. a = ro; // error!

函数类型:
为了使用接口表示函数类型,我们需要给接口定义一个调用签名。 它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。

  1. interface SearchFunc {
  2. (source: string, subString: string): boolean;
  3. }

这样定义后,我们可以像使用其它接口一样使用这个函数类型的接口。

  1. let mySearch: SearchFunc;
  2. mySearch = function(source: string, subString: string) {
  3. let result = source.search(subString);
  4. return result > -1;
  5. }

可索引类型:
与使用接口描述函数类型差不多,我们也可以描述那些能够“通过索引得到”的类型,比如a[10]或ageMap[“daniel”]。 可索引类型具有一个索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。

  1. // 定义了StringArray接口,它具有索引签名。
  2. // 这个索引签名表示了当用number去索引StringArray时会得到string类型的返回值。
  3. interface StringArray {
  4. [index: number]: string;
  5. }
  6. let myArray: StringArray;
  7. myArray = ["Bob", "Fred"];
  8. let myStr: string = myArray[0];

类类型:
接口描述了类的公共部分,而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员。

  1. interface ClockInterface {
  2. currentTime: Date;
  3. }
  4. class Clock implements ClockInterface {
  5. currentTime: Date;
  6. constructor(h: number, m: number) { }
  7. }