小白Ts -- 入门02

109 阅读7分钟

接口

  • TypeScript的核心原则之一是对值所具有的结构进行类型检查。在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

1.1 必填属性

// 常规写法
    function printLabel1(labelObj: { label: string }) {
      console.log(labelObj.label);
    }
    let myObj1 = { size: 10, label: "Size 10 Object" };
    printLabel1(myObj1);
    // 接口来描述:
    interface LabelledValue {
      label: string;
      value: number;
    }
    function printLabel2(labelledObj: LabelledValue) {
      console.log(labelledObj.label);
    }
    //Argument of type '{ size: number; label: string; }' is not assignable to parameter of type 'LabelledValue'.
    //Property 'value' is missing in type '{ size: number; label: string; }' but required in type 'LabelledValue'
    // let myObj2 = { size: 10, label: "Size 10 Object" };
    // printLabel2(myObj2); //error
    let myObj2 = { size: 10, label: "Size 10 Object", value: 1 };
    printLabel2(myObj2); // ok 
    

1.2 可选属性

  • 可选属性的好处:
  1. 可以对可能存在的属性进行预定义;
  2. 是可以捕获引用了不存在的属性时的错误。
   interface SquareConfig {
      color?: string;
      width?: number;
    }

    function createSquare(config: SquareConfig): { color: string; area: number } {
      let newSquare = { color: "white", area: 100 };
      // if (config.clor) {
      //   // Error: Property 'clor' does not exist on type 'SquareConfig'
      //   newSquare.color = config.clor;
      // }
      if (config.color) {
        newSquare.color = config.color;
      }
      if (config.width) {
        newSquare.area = config.width * config.width;
      }
      return newSquare;
    }

    let mySquare = createSquare({ color: "black" });
    

1.3 只读属性

  • 声明的属性不想让其更改值,可以在属性名前用 readonly来指定只读属性:
    interface Point {
      readonly x: number;
      readonly y: number;
    }
    // 可以通过赋值一个对象字面量来构造一个Point。 赋值后, x和y再也不能被改变了。
    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!
    

1.4 额外的属性检查

    interface SquareConfig {
        color?: string;
        width?: number;
    }
    function createSquare(config: SquareConfig): { color: string; area: number } {
        // ...
    }

    let mySquare = createSquare({ colour: "red", width: 100 }); // error: 'colour' not expected in type 'SquareConfig'
    
  • 对象字面量会被特殊对待而且会经过 额外属性检查,当将它们赋值给变量或作为参数传递的时候。 如果一个对象字面量存在任何“目标类型”不包含的属性时,你会得到一个错误。
  1. 绕开这些检查非常简单。 最简便的方法是使用类型断言:
    let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
  1. 最佳的方式是能够添加一个字符串索引签名
    interface SquareConfig {
      color?: string;
      width?: number;
      [propName: string]: any;
    }

1.5 函数类型

  • 给接口定义一个调用签名。参数列表里的每个参数都需要名字和类型。
    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;
    }

1.6 可索引的类型

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

    let myArray: StringArray;
    myArray = ["Bob", "Fred"];
    let myStr: string = myArray[0];
  • TypeScript支持两种索引签名:字符串和数字。
  • 可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用 number来索引时,JavaScript会将它转换成string然后再去索引对象。 也就是说用 100(一个number)去索引等同于使用"100"(一个string)去索引,因此两者需要保持一致。
    class Animal {
        name: string;
    }
    class Dog extends Animal {
        breed: string;
    }

    // 错误:使用数值型的字符串索引,有时会得到完全不同的Animal!
    interface NotOkay {
        [x: number]: Animal;
        [x: string]: Dog;
    }
  • 字符串索引签名能够很好的描述dictionary模式,并且它们也会确保所有属性与其返回值类型相匹配。 因为字符串索引声明了 obj.property和obj["property"]两种形式都可以。 下面的例子里, name的类型与字符串索引类型不匹配,所以类型检查器给出一个错误提示:
    interface NumberDictionary {
      [index: string]: number;
      length: number;    // 可以,length是number类型
      name: string       // 错误,`name`的类型与索引类型返回值的类型不匹配
    }
  • 同时也可以将索引签名设置为只读,这样就防止了给索引赋值
    interface ReadonlyStringArray {
        readonly [index: number]: string;
    }
    let myArray: ReadonlyStringArray = ["Alice", "Bob"];
    myArray[2] = "Mallory"; // error!

1.7 类类型

  • 1.7.1 实现接口 (TypeScript能够用它来明确的强制一个类去符合某种契约)
    interface ClockInterface {
      currentTime: Date;
    }

    class Clock implements ClockInterface {
      currentTime: Date;
      constructor(h: number, m: number) { }
    }

可以在接口中描述一个方法,在类里实现它,如同下面的setTime方法一样:

    interface ClockInterface {
      currentTime: Date;
      setTime(d: Date);
    }

    class Clock implements ClockInterface {
      currentTime: Date;
      setTime(d: Date) {
          this.currentTime = d;
      }
      constructor(h: number, m: number) { }
    }
  • 1.7.2 类静态部分与实例部分的区别

    当你操作类和接口的时候,你要知道类是具有两个类型的:静态部分的类型和实例的类型。 你会注意到,当你用构造器签名去定义一个接口并试图定义一个类去实现这个接口时会得到一个错误:

    interface ClockConstructor {
      new (hour: number, minute: number);
    }

    class Clock implements ClockConstructor {
      currentTime: Date;
      constructor(h: number, m: number) { }
    }

这里因为当一个类实现了一个接口时,只对其实例部分进行类型检查。 constructor存在于类的静态部分,所以不在检查的范围内。

因此,我们应该直接操作类的静态部分。 看下面的例子,我们定义了两个接口, ClockConstructor为构造函数所用和ClockInterface为实例方法所用。 为了方便我们定义一个构造函数 createClock,它用传入的类型创建实例。

    interface ClockConstructor {
        new (hour: number, minute: number): ClockInterface;
    }
    interface ClockInterface {
        tick();
    }

    function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
        return new ctor(hour, minute);
    }

    class DigitalClock implements ClockInterface {
        constructor(h: number, m: number) { }
        tick() {
            console.log("beep beep");
        }
    }
    class AnalogClock implements ClockInterface {
        constructor(h: number, m: number) { }
        tick() {
            console.log("tick tock");
        }
    }

    let digital = createClock(DigitalClock, 12, 17);
    let analog = createClock(AnalogClock, 7, 32);

1.8 继承接口

    interface Shape {
        color: string;
    }

    interface Square extends Shape {
        sideLength: number;
    }

    let square = <Square>{};
    square.color = "blue";
    square.sideLength = 10;
  • 也可以继承多个接口,创建出多个接口的合成接口
    interface PenStroke {
        penWidth: number;
    }
    interface Square extends Shape, PenStroke {
        sideLength: number;
    }
    square.penWidth = 5.0;

1.9 混合类型

  • 一个对象可以同时做为函数和对象使用,并带有额外的属性
    interface Counter {
        (start: number): string;
        interval: number;
        reset(): void;
    }

    function getCounter(): Counter {
        let counter = <Counter>function (start: number) { };
        counter.interval = 123;
        counter.reset = function () { };
        return counter;
    }

    let c = getCounter();
    c(10);
    c.reset();
    c.interval = 5.0;

1.10 接口继承类

  • 当接口继承了一个类类型时,它会继承类的成员但不包括其实现。 就好像接口声明了所有类中存在的成员,但并没有提供具体实现一样。 接口同样会继承到类的private和protected成员。 这意味着当你创建了一个接口继承了一个拥有私有或受保护的成员的类时,这个接口类型只能被这个类或其子类所实现(implement)。

  • 当你有一个庞大的继承结构时这很有用,但要指出的是你的代码只在子类拥有特定属性时起作用。 这个子类除了继承至基类外与基类没有任何关系。 例:

    class Control {
        private state: any;
    }

    interface SelectableControl extends Control {
        select(): void;
    }

    class Button extends Control implements SelectableControl {
        select() { }
    }

    class TextBox extends Control {
        select() { }
    }

    // 错误:“Image”类型缺少“state”属性。
    class Image implements SelectableControl {
        select() { }
    }

    class Location {

    }

在上面的例子里,SelectableControl包含了Control的所有成员,包括私有成员state。 因为 state是私有成员,所以只能够是Control的子类们才能实现SelectableControl接口。 因为只有 Control的子类才能够拥有一个声明于Control的私有成员state,这对私有成员的兼容性是必需的。

在Control类内部,是允许通过SelectableControl的实例来访问私有成员state的。 实际上, SelectableControl接口和拥有select方法的Control类是一样的。 Button和TextBox类是SelectableControl的子类(因为它们都继承自Control并有select方法),但Image和Location类并不是这样的。