• 转载:《TypeScript 中文入门教程》 3、接口


    版权

    文章转载自:https://github.com/zhongsp

    建议您直接跳转到上面的网址查看最新版本。

    介绍

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

    接口初探

    下面通过一个简单示例来观察接口是如何工作的:

    function printLabel(labelledObj: { label: string }) {
      console.log(labelledObj.label);
    }
    
    var myObj = { size: 10, label: "Size 10 Object" };
    printLabel(myObj);

    类型检查器会查看printLabel的调用。 printLabel有一个参数,并要求这个对象参数有一个名为label类型为string的属性。 需要注意的是,我们传入的对象参数实际上会包含很多属性,但是编译器只会检查那些必需的属性是否存在,并且其类型是否匹配。

    下面我们重写上面的例子,这次使用接口来描述:必须包含一个label属性且类型为string

    interface LabelledValue {
      label: string;
    }
    
    function printLabel(labelledObj: LabelledValue) {
      console.log(labelledObj.label);
    }
    
    var myObj = {size: 10, label: "Size 10 Object"};
    printLabel(myObj);

    LabelledValue接口就好比一个名字,用来描述上面例子里的要求。 它代表了有一个label属性且类型为string的对象。 需要注意的是,我们在这里并不能像在其它语言里一样,说传给printLabel的对象实现了这个接口。我们只会去关注值的外形。 只要传入的对象满足上面提到的必要条件,那么它就是被允许的。

    还有一点值得提的是,类型检查器不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以。

    可选属性

    接口里的属性不全都是必需的。 有些是只在某些条件下存在,或者根本不存在。 可选属性在应用“option bags”模式时很常用,即给函数传入的参数对象中只有部分属性赋值了。

    下面是应用了“option bags”的例子:

    interface SquareConfig {
      color?: string;
      width?: number;
    }
    
    function createSquare(config: SquareConfig): {color: string; area: number} {
      var newSquare = {color: "white", area: 100};
      if (config.color) {
        newSquare.color = config.color;
      }
      if (config.width) {
        newSquare.area = config.width * config.width;
      }
      return newSquare;
    }
    
    var mySquare = createSquare({color: "black"});

    带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?符号。

    可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误。 比如,我们故意将createSquare里的color属性名拼错,就会得到一个错误提示:

    interface SquareConfig {
      color?: string;
      width?: number;
    }
    
    function createSquare(config: SquareConfig): {color: string; area: number} {
      var newSquare = {color: "white", area: 100};
      if (config.color) {
        // Error: Property 'collor' does not exist on type 'SquareConfig'
        newSquare.color = config.collor;  // Type-checker can catch the mistyped name here
      }
      if (config.width) {
        newSquare.area = config.width * config.width;
      }
      return newSquare;
    }
    
    var mySquare = createSquare({color: "black"});

    函数类型

    接口能够描述JavaScript中对象拥有的各种各样的外形。 除了描述带有属性的普通对象外,接口也可以描述函数类型。

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

    interface SearchFunc {
      (source: string, subString: string): boolean;
    }

    这样定义后,我们可以像使用其它接口一样使用这个函数类型的接口。 下例展示了如何创建一个函数类型的变量,并将一个同类型的函数赋值给这个变量。

    var mySearch: SearchFunc;
    mySearch = function(source: string, subString: string) {
      var result = source.search(subString);
      if (result == -1) {
        return false;
      }
      else {
        return true;
      }
    }

    对于函数类型的类型检查来说,函数的参数名不需要与接口里定义的名字相匹配。 比如,我们使用下面的代码重写上面的例子:

    var mySearch: SearchFunc;
    mySearch = function(src: string, sub: string): boolean {
      var result = src.search(sub);
      if (result == -1) {
        return false;
      }
      else {
        return true;
      }
    }

    函数的参数会逐个进行检查,要求对应位置上的参数类型是兼容的。 如果你不想指定类型,Typescript的类型系统会推断出参数类型,因为函数直接赋值给了SearchFunc类型变量。 函数的返回值类型是通过其返回值推断出来的(此例是falsetrue)。 如果让这个函数返回数字或字符串,类型检查器会警告我们函数的返回值类型与SearchFunc接口中的定义不匹配。

    var mySearch: SearchFunc;
    mySearch = function(src, sub) {
        var result = src.search(sub);
        if (result == -1) {
            return false;
        }
        else {
            return true;
        }
    }

    数组类型

    与使用接口描述函数类型差不多,我们也可以描述数组类型。 数组类型具有一个index类型表示索引的类型,还有一个相应的返回值类型表示通过索引得到的元素的类型。

    interface StringArray {
      [index: number]: string;
    }
    
    var myArray: StringArray;
    myArray = ["Bob", "Fred"];

    支持两种索引类型:string和number。 数组可以同时使用这两种索引类型,但是有一个限制,数字索引返回值的类型必须是字符串索引返回值的类型的子类型。

    索引签名能够很好的描述数组和dictionary模式,它们也要求所有属性要与返回值类型相匹配。 因为字符串索引表明obj.propertyobj["property"]两种形式都可以。 下面的例子里,name的类型与字符串索引类型不匹配,所以类型检查器给出一个错误提示:

    interface NumberDictionary {
      [index: string]: number;
      length: number;    // 可以,length是number类型
      name: string       // 错误,`name`的类型不是索引类型的子类型
    }

    类类型

    实现接口

    与C#或Java里接口的基本作用一样,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) { }
    }

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

    类静态部分与实例部分的区别

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

    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");
        }
    }
    
    var digital = createClock(DigitalClock, 12, 17);
    var analog = createClock(AnalogClock, 7, 32);

    因为createClock的第一个参数是ClockConstructor类型,在createClock(AnalogClock, 12, 17)里,会检查AnalogClock是否符合构造函数签名。

    扩展接口

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

    interface Shape {
        color: string;
    }
    
    interface Square extends Shape {
        sideLength: number;
    }
    
    var square = <Square>{};
    square.color = "blue";
    square.sideLength = 10;

    一个接口可以继承多个接口,创建出多个接口的合成接口。

    interface Shape {
        color: string;
    }
    
    interface PenStroke {
        penWidth: number;
    }
    
    interface Square extends Shape, PenStroke {
        sideLength: number;
    }
    
    var square = <Square>{};
    square.color = "blue";
    square.sideLength = 10;
    square.penWidth = 5.0;

    混合类型

    先前我们提过,接口能够描述JavaScript里丰富的类型。 因为JavaScript其动态灵活的特点,有时你会希望一个对象可以同时具有上面提到的多种类型。

    一个例子就是,一个对象可以同时做为函数和对象使用,并带有额外的属性。

    interface Counter {
        (start: number): string;
        interval: number;
        reset(): void;
    }
    
    function getCounter(): Counter {
        var counter = <Counter>function (start: number) { };
        counter.interval = 123;
        counter.reset = function () { };
        return counter;
    }
    
    var c = getCounter();
    c(10);
    c.reset();
    c.interval = 5.0;

    在使用JavaScript第三方库的时候,你可能需要像上面那样去完整地定义类型。

    接口继承类

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

    这是很有用的,当你有一个很深层次的继承,但是只想你的代码只是针对拥有特定属性的子类起作用的时候。子类除了继承自基类外与基类没有任何联系。 例:

    class Control {  
        private state: any; 
    }
    
    interface SelectableControl extends Control {  
        select(): void;  
    }
    
    class Button extends Control {  
        select() { }  
    }
    class TextBox extends Control {  
        select() { }  
    }
    class Image extends Control {  
    }
    class Location {  
        select() { }  
    }

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

    Control类内部,是允许通过SelectableControl的实例来访问私有成员state的。 实际上,SelectableControl就像Control一样,并拥有一个select方法。 ButtonTextBox类是SelectableControl的子类(类为它们都继承自Control并有select方法),但ImageLocation类并不是这样的。

  • 相关阅读:
    【前端技术文章阅读】--201608
    极简版 react+webpack 脚手架
    《JavaScript模式》第6章 代码复用模式
    《JavaScript模式》第5章 对象创建模式
    《JavaScript模式》第4章 函数
    《JavaScript模式》第3章 字面量和构造函数
    简版导航栏实现
    2014年第五届蓝桥杯试题C/C++程序设计B组——李白打酒
    2014第五届蓝桥杯试题C/C++程序设计B组——切面条
    2014年第五届蓝桥杯试题——啤酒和饮料
  • 原文地址:https://www.cnblogs.com/tansm/p/TypeScript_Handbook_Interfaces.html
Copyright © 2020-2023  润新知