介绍

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

interface

使用interface定义,
例子:

  1. interface Iprops {
  2. name: string;
  3. age: number;
  4. }
  5. function person(obj: Iprops) {
  6. console.log(obj.name);
  7. }
  8. let myObj = {name: 'mike', age: 10};
  9. person(myObj);

可选属性

有的值可有可无,在名称后面添加符号
可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误

  1. interface Iprops {
  2. name: string;
  3. age?: number;
  4. }
  5. function person(obj: Iprops) {
  6. console.log(obj.name);
  7. }
  8. let myObj = {name: 'mike'};
  9. person(myObj);

只读属性

一些对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 readonly来指定只读属性:
你可以通过赋值一个对象字面量来构造一个Point。 赋值后, x和y再也不能被改变了。可以想象成定义一个常量,类似const
最简单判断该用readonly还是const的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 const,若做为属性则使用readonly

  1. interface Point {
  2. readonly x: number;
  3. readonly y: number;
  4. }
  5. let p1: Point = { x: 10, y: 20 };
  6. p1.x = 5; // error!

函数类型

接口能够描述JavaScript中对象拥有的各种各样的外形。 除了描述带有属性的普通对象外,接口也可以描述函数类型。
为了使用接口表示函数类型,我们需要给接口定义一个调用签名。 它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。

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

可索引的类型

可索引类型具有一个 索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。 让我们看一个例子:

  1. interface StringArray {
  2. [index: number]: string;
  3. }
  4. let myArray: StringArray;
  5. myArray = ["Bob", "Fred"];
  6. let myStr: string = myArray[0];

继承接口

和类一样,接口也可以相互继承。 这让我们能够从一个接口里复制成员到另一个接口里,可以更灵活地将接口分割到可重用的模块里,一个接口可以继承多个接口,创建出多个接口的合成接口。

  1. interface Shape {
  2. color: string;
  3. }
  4. interface PenStroke {
  5. penWidth: number;
  6. }
  7. interface Square extends Shape, PenStroke {
  8. sideLength: number;
  9. }
  10. let square = <Square>{};
  11. square.color = "blue";
  12. square.sideLength = 10;
  13. square.penWidth = 5.0;

混合类型

  1. interface Counter {
  2. (start: number): string;
  3. interval: number;
  4. reset(): void;
  5. }
  6. function getCounter(): Counter {
  7. let counter = <Counter>function (start: number) { };
  8. counter.interval = 123;
  9. counter.reset = function () { };
  10. return counter;
  11. }
  12. let c = getCounter();
  13. c(10);
  14. c.reset();
  15. c.interval = 5.0;