诗怡一昂 發表於 2020-9-5 23:43:00

TypeScript学习(二) - TypeScript的接口(interface)和类(class)

<ul>
<li>1. 对象的类型——接口
<ul>
<li>1.1 什么是接口</li>
<li>1.2 简单的例子</li>
<li>1.3 可选属性</li>
<li>1.4 任意属性</li>
<li>1.5 只读属性</li>
</ul>
</li>
<li>2. 类
<ul>
<li>2.1 类的概念</li>
<li>2.2 ES6 中类的用法
<ul>
<li> 属性和方法</li>
<li> 类的继承</li>
<li> 存取器</li>
<li> 静态方法</li>
</ul>
</li>
<li>2.3 ES7 中类的用法
<ul>
<li> 实例属性</li>
<li> 静态属性</li>
</ul>
</li>
<li>2.4 TypeScript 中类的用法
<ul>
<li>public private 和 protected</li>
<li> 参数属性</li>
<li> readonly</li>
<li> 抽象类</li>
</ul>
</li>
<li>2.5 类的类型</li>
</ul>
</li>
<li>3. 类与接口
<ul>
<li>3.1 类实现接口</li>
<li>3.2 接口继承接口</li>
<li>3.3 接口继承类</li>
</ul>
</li>
</ul>
<h2 id="1-对象的类型接口"><span id="head1">1. 对象的类型——接口</span></h2>
<p>在 TypeScript 中,我们使用接口(Interfaces)来定义对象的类型。</p>
<h3 id="11-什么是接口"><span id="head2">1.1 什么是接口</span></h3>
<p>在面向对象语言中,接口(Interfaces)是一个很重要的概念,它是对行为的抽象,而具体如何行动需要由类(classes)去实现(implement)。</p>
<p>TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。</p>
<h3 id="12-简单的例子"><span id="head3">1.2 简单的例子</span></h3>
<pre><code class="language-ts">interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom',
    age: 25
};
</code></pre>
<p>上面的例子中,我们定义了一个接口 <code>Person</code>,接着定义了一个变量 <code>tom</code>,它的类型是 <code>Person</code>。这样,我们就约束了 <code>tom</code> 的形状必须和接口 <code>Person</code> 一致。</p>
<p>接口一般首字母大写。有的编程语言中会建议接口的名称加上 <code>I</code> 前缀。</p>
<p>定义的变量比接口少了一些属性是不允许的:</p>
<pre><code class="language-ts">interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom'
};

// index.ts(6,5): error TS2322: Type '{ name: string; }' is not assignable to type 'Person'.
//   Property 'age' is missing in type '{ name: string; }'.
</code></pre>
<p>多一些属性也是不允许的:</p>
<pre><code class="language-ts">interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
};

// index.ts(9,5): error TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'.
//   Object literal may only specify known properties, and 'gender' does not exist in type 'Person'.
</code></pre>
<p>可见,<strong>赋值的时候,变量的形状必须和接口的形状保持一致</strong>。</p>
<h3 id="13-可选属性"><span id="head4">1.3 可选属性</span></h3>
<p>有时我们希望不要完全匹配一个形状,那么可以用可选属性:</p>
<pre><code class="language-ts">interface Person {
    name: string;
    age?: number;
}

let tom: Person = {
    name: 'Tom'
};
</code></pre>
<pre><code class="language-ts">interface Person {
    name: string;
    age?: number;
}

let tom: Person = {
    name: 'Tom',
    age: 25
};
</code></pre>
<p>可选属性的含义是该属性可以不存在。</p>
<p>这时<strong>仍然不允许添加未定义的属性</strong>:</p>
<pre><code class="language-ts">interface Person {
    name: string;
    age?: number;
}

let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
};

// examples/playground/index.ts(9,5): error TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'.
//   Object literal may only specify known properties, and 'gender' does not exist in type 'Person'.
</code></pre>
<h3 id="14-任意属性"><span id="head5">1.4 任意属性</span></h3>
<p>有时候我们希望一个接口允许有任意的属性,可以使用如下方式:</p>
<pre><code class="language-ts">interface Person {
    name: string;
    age?: number;
    : any;
}

let tom: Person = {
    name: 'Tom',
    gender: 'male'
};
</code></pre>
<p>使用 <code></code> 定义了任意属性取 <code>string</code> 类型的值。</p>
<p>需要注意的是,<strong>一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集</strong>:</p>
<pre><code class="language-ts">interface Person {
    name: string;
    age?: number;
    : string;
}

let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
};

// index.ts(3,5): error TS2411: Property 'age' of type 'number' is not assignable to string index type 'string'.
// index.ts(7,5): error TS2322: Type '{ : string | number; name: string; age: number; gender: string; }' is not assignable to type 'Person'.
//   Index signatures are incompatible.
//   Type 'string | number' is not assignable to type 'string'.
//       Type 'number' is not assignable to type 'string'.
</code></pre>
<p>上例中,任意属性的值允许是 <code>string</code>,但是可选属性 <code>age</code> 的值却是 <code>number</code>,<code>number</code> 不是 <code>string</code> 的子属性,所以报错了。</p>
<p>另外,在报错信息中可以看出,此时 <code>{ name: 'Tom', age: 25, gender: 'male' }</code> 的类型被推断成了 <code>{ : string | number; name: string; age: number; gender: string; }</code>,这是联合类型和接口的结合。</p>
<p>一个接口中只能定义一个任意属性。如果接口中有多个类型的属性,则可以在任意属性中使用联合类型:</p>
<pre><code class="language-ts">interface Person {
    name: string;
    age?: number;
    : string | number;
}

let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
};
</code></pre>
<h3 id="15-只读属性"><span id="head6">1.5 只读属性</span></h3>
<p>有时候我们希望对象中的一些字段只能在创建的时候被赋值,那么可以用 <code>readonly</code> 定义只读属性:</p>
<pre><code class="language-ts">interface Person {
    readonly id: number;
    name: string;
    age?: number;
    : any;
}

let tom: Person = {
    id: 89757,
    name: 'Tom',
    gender: 'male'
};

tom.id = 9527;

// index.ts(14,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.
</code></pre>
<p>上例中,使用 <code>readonly</code> 定义的属性 <code>id</code> 初始化后,又被赋值了,所以报错了。</p>
<p><strong>注意,只读的约束存在于第一次给对象赋值的时候,而不是第一次给只读属性赋值的时候</strong>:</p>
<pre><code class="language-ts">interface Person {
    readonly id: number;
    name: string;
    age?: number;
    : any;
}

let tom: Person = {
    name: 'Tom',
    gender: 'male'
};

tom.id = 89757;

// index.ts(8,5): error TS2322: Type '{ name: string; gender: string; }' is not assignable to type 'Person'.
//   Property 'id' is missing in type '{ name: string; gender: string; }'.
// index.ts(13,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.
</code></pre>
<p>上例中,报错信息有两处,第一处是在对 <code>tom</code> 进行赋值的时候,没有给 <code>id</code> 赋值。</p>
<p>第二处是在给 <code>tom.id</code> 赋值的时候,由于它是只读属性,所以报错了。</p>
<h2 id="2-类"><span id="head7">2. 类</span></h2>
<p>传统方法中,JavaScript 通过构造函数实现类的概念,通过原型链实现继承。而在 ES6 中,我们终于迎来了 <code>class</code>。</p>
<p>TypeScript 除了实现了所有 ES6 中的类的功能以外,还添加了一些新的用法。</p>
<p>这一节主要介绍类的用法,下一节再介绍如何定义类的类型。</p>
<h3 id="21-类的概念"><span id="head8">2.1 类的概念</span></h3>
<p>虽然 JavaScript 中有类的概念,但是可能大多数 JavaScript 程序员并不是非常熟悉类,这里对类相关的概念做一个简单的介绍。</p>
<ul>
<li>类(Class):定义了一件事物的抽象特点,包含它的属性和方法</li>
<li>对象(Object):类的实例,通过 <code>new</code> 生成</li>
<li>面向对象(OOP)的三大特性:封装、继承、多态</li>
<li>封装(Encapsulation):将对数据的操作细节隐藏起来,只暴露对外的接口。外界调用端不需要(也不可能)知道细节,就能通过对外提供的接口来访问该对象,同时也保证了外界无法任意更改对象内部的数据</li>
<li>继承(Inheritance):子类继承父类,子类除了拥有父类的所有特性外,还有一些更具体的特性</li>
<li>多态(Polymorphism):由继承而产生了相关的不同的类,对同一个方法可以有不同的响应。比如 <code>Cat</code> 和 <code>Dog</code> 都继承自 <code>Animal</code>,但是分别实现了自己的 <code>eat</code> 方法。此时针对某一个实例,我们无需了解它是 <code>Cat</code> 还是 <code>Dog</code>,就可以直接调用 <code>eat</code> 方法,程序会自动判断出来应该如何执行 <code>eat</code></li>
<li>存取器(getter &amp; setter):用以改变属性的读取和赋值行为</li>
<li>修饰符(Modifiers):修饰符是一些关键字,用于限定成员或类型的性质。比如 <code>public</code> 表示公有属性或方法</li>
<li>抽象类(Abstract Class):抽象类是供其他类继承的基类,抽象类不允许被实例化。抽象类中的抽象方法必须在子类中被实现</li>
<li>接口(Interfaces):不同类之间公有的属性或方法,可以抽象成一个接口。接口可以被类实现(implements)。一个类只能继承自另一个类,但是可以实现多个接口</li>
</ul>
<h3 id="22-es6-中类的用法"><span id="head9">2.2 ES6 中类的用法</span></h3>
<p>下面我们先回顾一下 ES6 中类的用法,更详细的介绍可以参考 。</p>
<h4 id="-属性和方法"><span id="head10"> 属性和方法</span></h4>
<p>使用 <code>class</code> 定义类,使用 <code>constructor</code> 定义构造函数。</p>
<p>通过 <code>new</code> 生成新实例的时候,会自动调用构造函数。</p>
<pre><code class="language-js">class Animal {
    public name;
    constructor(name) {
      this.name = name;
    }
    sayHi() {
      return `My name is ${this.name}`;
    }
}

let a = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
</code></pre>
<h4 id="-类的继承"><span id="head11"> 类的继承</span></h4>
<p>使用 <code>extends</code> 关键字实现继承,子类中使用 <code>super</code> 关键字来调用父类的构造函数和方法。</p>
<pre><code class="language-js">class Cat extends Animal {
constructor(name) {
    super(name); // 调用父类的 constructor(name)
    console.log(this.name);
}
sayHi() {
    return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi()
}
}

let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
</code></pre>
<h4 id="-存取器"><span id="head12"> 存取器</span></h4>
<p>使用 getter 和 setter 可以改变属性的赋值和读取行为:</p>
<pre><code class="language-js">class Animal {
constructor(name) {
    this.name = name;
}
get name() {
    return 'Jack';
}
set name(value) {
    console.log('setter: ' + value);
}
}

let a = new Animal('Kitty'); // setter: Kitty
a.name = 'Tom'; // setter: Tom
console.log(a.name); // Jack
</code></pre>
<h4 id="-静态方法"><span id="head13"> 静态方法</span></h4>
<p>使用 <code>static</code> 修饰符修饰的方法称为静态方法,它们不需要实例化,而是直接通过类来调用:</p>
<pre><code class="language-js">class Animal {
static isAnimal(a) {
    return a instanceof Animal;
}
}

let a = new Animal('Jack');
Animal.isAnimal(a); // true
a.isAnimal(a); // TypeError: a.isAnimal is not a function
</code></pre>
<h3 id="23-es7-中类的用法"><span id="head14">2.3 ES7 中类的用法</span></h3>
<p>ES7 中有一些关于类的提案,TypeScript 也实现了它们,这里做一个简单的介绍。</p>
<h4 id="-实例属性"><span id="head15"> 实例属性</span></h4>
<p>ES6 中实例的属性只能通过构造函数中的 <code>this.xxx</code> 来定义,ES7 提案中可以直接在类里面定义:</p>
<pre><code class="language-js">class Animal {
name = 'Jack';

constructor() {
    // ...
}
}

let a = new Animal();
console.log(a.name); // Jack
</code></pre>
<h4 id="-静态属性"><span id="head16"> 静态属性</span></h4>
<p>ES7 提案中,可以使用 <code>static</code> 定义一个静态属性:</p>
<pre><code class="language-js">class Animal {
static num = 42;

constructor() {
    // ...
}
}

console.log(Animal.num); // 42
</code></pre>
<h3 id="24-typescript-中类的用法"><span id="head17">2.4 TypeScript 中类的用法</span></h3>
<h4 id="public-private-和-protected"><span id="head18">public private 和 protected</span></h4>
<p>TypeScript 可以使用三种访问修饰符(Access Modifiers),分别是 <code>public</code>、<code>private</code> 和 <code>protected</code>。</p>
<ul>
<li><code>public</code> 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 <code>public</code> 的</li>
<li><code>private</code> 修饰的属性或方法是私有的,不能在声明它的类的外部访问</li>
<li><code>protected</code> 修饰的属性或方法是受保护的,它和 <code>private</code> 类似,区别是它在子类中也是允许被访问的</li>
</ul>
<p>下面举一些例子:</p>
<pre><code class="language-ts">class Animal {
public name;
public constructor(name) {
    this.name = name;
}
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom
</code></pre>
<p>上面的例子中,<code>name</code> 被设置为了 <code>public</code>,所以直接访问实例的 <code>name</code> 属性是允许的。</p>
<p>很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 <code>private</code> 了:</p>
<pre><code class="language-ts">class Animal {
private name;
public constructor(name) {
    this.name = name;
}
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
// index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
</code></pre>
<p>需要注意的是,TypeScript 编译之后的代码中,并没有限制 <code>private</code> 属性在外部的可访问性。</p>
<p>上面的例子编译后的代码是:</p>
<pre><code class="language-js">var Animal = (function () {
function Animal(name) {
    this.name = name;
}
return Animal;
})();
var a = new Animal('Jack');
console.log(a.name);
a.name = 'Tom';
</code></pre>
<p>使用 <code>private</code> 修饰的属性或方法,在子类中也是不允许访问的:</p>
<pre><code class="language-ts">class Animal {
private name;
public constructor(name) {
    this.name = name;
}
}

class Cat extends Animal {
constructor(name) {
    super(name);
    console.log(this.name);
}
}

// index.ts(11,17): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
</code></pre>
<p>而如果是用 <code>protected</code> 修饰,则允许在子类中访问:</p>
<pre><code class="language-ts">class Animal {
protected name;
public constructor(name) {
    this.name = name;
}
}

class Cat extends Animal {
constructor(name) {
    super(name);
    console.log(this.name);
}
}
</code></pre>
<p>当构造函数修饰为 <code>private</code> 时,该类不允许被继承或者实例化:</p>
<pre><code class="language-ts">class Animal {
public name;
private constructor(name) {
    this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
    super(name);
}
}

let a = new Animal('Jack');

// index.ts(7,19): TS2675: Cannot extend a class 'Animal'. Class constructor is marked as private.
// index.ts(13,9): TS2673: Constructor of class 'Animal' is private and only accessible within the class declaration.
</code></pre>
<p>当构造函数修饰为 <code>protected</code> 时,该类只允许被继承:</p>
<pre><code class="language-ts">class Animal {
public name;
protected constructor(name) {
    this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
    super(name);
}
}

let a = new Animal('Jack');

// index.ts(13,9): TS2674: Constructor of class 'Animal' is protected and only accessible within the class declaration.
</code></pre>
<h4 id="-参数属性"><span id="head19"> 参数属性</span></h4>
<p>修饰符和<code>readonly</code>还可以使用在构造函数参数中,等同于类中定义该属性同时给该属性赋值,使代码更简洁。</p>
<pre><code class="language-ts">class Animal {
// public name: string;
public constructor(public name) {
    // this.name = name;
}
}
</code></pre>
<h4 id="-readonly"><span id="head20"> readonly</span></h4>
<p>只读属性关键字,只允许出现在属性声明或索引签名或构造函数中。</p>
<pre><code class="language-ts">class Animal {
readonly name;
public constructor(name) {
    this.name = name;
}
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.
</code></pre>
<p>注意如果 <code>readonly</code> 和其他访问修饰符同时存在的话,需要写在其后面。</p>
<pre><code class="language-ts">class Animal {
// public readonly name;
public constructor(public readonly name) {
    // this.name = name;
}
}
</code></pre>
<h4 id="-抽象类"><span id="head21"> 抽象类</span></h4>
<p><code>abstract</code> 用于定义抽象类和其中的抽象方法。</p>
<p>什么是抽象类?</p>
<p>首先,抽象类是不允许被实例化的:</p>
<pre><code class="language-ts">abstract class Animal {
public name;
public constructor(name) {
    this.name = name;
}
public abstract sayHi();
}

let a = new Animal('Jack');

// index.ts(9,11): error TS2511: Cannot create an instance of the abstract class 'Animal'.
</code></pre>
<p>上面的例子中,我们定义了一个抽象类 <code>Animal</code>,并且定义了一个抽象方法 <code>sayHi</code>。在实例化抽象类的时候报错了。</p>
<p>其次,抽象类中的抽象方法必须被子类实现:</p>
<pre><code class="language-ts">abstract class Animal {
public name;
public constructor(name) {
    this.name = name;
}
public abstract sayHi();
}

class Cat extends Animal {
public eat() {
    console.log(`${this.name} is eating.`);
}
}

let cat = new Cat('Tom');

// index.ts(9,7): error TS2515: Non-abstract class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'.
</code></pre>
<p>上面的例子中,我们定义了一个类 <code>Cat</code> 继承了抽象类 <code>Animal</code>,但是没有实现抽象方法 <code>sayHi</code>,所以编译报错了。</p>
<p>下面是一个正确使用抽象类的例子:</p>
<pre><code class="language-ts">abstract class Animal {
public name;
public constructor(name) {
    this.name = name;
}
public abstract sayHi();
}

class Cat extends Animal {
public sayHi() {
    console.log(`Meow, My name is ${this.name}`);
}
}

let cat = new Cat('Tom');
</code></pre>
<p>上面的例子中,我们实现了抽象方法 <code>sayHi</code>,编译通过了。</p>
<p>需要注意的是,即使是抽象方法,TypeScript 的编译结果中,仍然会存在这个类,上面的代码的编译结果是:</p>
<pre><code class="language-js">var __extends =
(this &amp;&amp; this.__extends) ||
function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d = b;
    function __() {
      this.constructor = d;
    }
    d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
};
var Animal = (function () {
function Animal(name) {
    this.name = name;
}
return Animal;
})();
var Cat = (function (_super) {
__extends(Cat, _super);
function Cat() {
    _super.apply(this, arguments);
}
Cat.prototype.sayHi = function () {
    console.log('Meow, My name is ' + this.name);
};
return Cat;
})(Animal);
var cat = new Cat('Tom');
</code></pre>
<h3 id="25-类的类型"><span id="head22">2.5 类的类型</span></h3>
<p>给类加上 TypeScript 的类型很简单,与接口类似:</p>
<pre><code class="language-ts">class Animal {
name: string;
constructor(name: string) {
    this.name = name;
}
sayHi(): string {
    return `My name is ${this.name}`;
}
}

let a: Animal = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
</code></pre>
<h2 id="3-类与接口"><span id="head23">3. 类与接口</span></h2>
<p>之前学习过,接口(Interfaces)可以用于对「对象的形状(Shape)」进行描述。</p>
<p>这一章主要介绍接口的另一个用途,对类的一部分行为进行抽象。</p>
<h3 id="31-类实现接口"><span id="head24">3.1 类实现接口</span></h3>
<p>实现(implements)是面向对象中的一个重要概念。一般来讲,一个类只能继承自另一个类,有时候不同类之间可以有一些共有的特性,这时候就可以把特性提取成接口(interfaces),用 <code>implements</code> 关键字来实现。这个特性大大提高了面向对象的灵活性。</p>
<p>举例来说,门是一个类,防盗门是门的子类。如果防盗门有一个报警器的功能,我们可以简单的给防盗门添加一个报警方法。这时候如果有另一个类,车,也有报警器的功能,就可以考虑把报警器提取出来,作为一个接口,防盗门和车都去实现它:</p>
<pre><code class="language-ts">interface Alarm {
    alert(): void;
}

class Door {
}

class SecurityDoor extends Door implements Alarm {
    alert() {
      console.log('SecurityDoor alert');
    }
}

class Car implements Alarm {
    alert() {
      console.log('Car alert');
    }
}
</code></pre>
<p>一个类可以实现多个接口:</p>
<pre><code class="language-ts">interface Alarm {
    alert(): void;
}

interface Light {
    lightOn(): void;
    lightOff(): void;
}

class Car implements Alarm, Light {
    alert() {
      console.log('Car alert');
    }
    lightOn() {
      console.log('Car light on');
    }
    lightOff() {
      console.log('Car light off');
    }
}
</code></pre>
<p>上例中,<code>Car</code> 实现了 <code>Alarm</code> 和 <code>Light</code> 接口,既能报警,也能开关车灯。</p>
<h3 id="32-接口继承接口"><span id="head25">3.2 接口继承接口</span></h3>
<p>接口与接口之间可以是继承关系:</p>
<pre><code class="language-ts">interface Alarm {
    alert(): void;
}

interface LightableAlarm extends Alarm {
    lightOn(): void;
    lightOff(): void;
}
</code></pre>
<p>这很好理解,<code>LightableAlarm</code> 继承了 <code>Alarm</code>,除了拥有 <code>alert</code> 方法之外,还拥有两个新方法 <code>lightOn</code> 和 <code>lightOff</code>。</p>
<h3 id="33-接口继承类"><span id="head26">3.3 接口继承类</span></h3>
<p>常见的面向对象语言中,接口是不能继承类的,但是在 TypeScript 中却是可以的:</p>
<pre><code class="language-ts">class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
      this.x = x;
      this.y = y;
    }
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};
</code></pre>
<p>为什么 TypeScript 会支持接口继承类呢?</p>
<p>实际上,当我们在声明 <code>class Point</code> 时,除了会创建一个名为 <code>Point</code> 的类之外,同时也创建了一个名为 <code>Point</code> 的类型(实例的类型)。</p>
<p>所以我们既可以将 <code>Point</code> 当做一个类来用(使用 <code>new Point</code> 创建它的实例):</p>
<pre><code class="language-ts">class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
      this.x = x;
      this.y = y;
    }
}

const p = new Point(1, 2);
</code></pre>
<p>也可以将 <code>Point</code> 当做一个类型来用(使用 <code>: Point</code> 表示参数的类型):</p>
<pre><code class="language-ts">class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
      this.x = x;
      this.y = y;
    }
}

function printPoint(p: Point) {
    console.log(p.x, p.y);
}

printPoint(new Point(1, 2));
</code></pre>
<p>这个例子实际上可以等价于:</p>
<pre><code class="language-ts">class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
      this.x = x;
      this.y = y;
    }
}

interface PointInstanceType {
    x: number;
    y: number;
}

function printPoint(p: PointInstanceType) {
    console.log(p.x, p.y);
}

printPoint(new Point(1, 2));
</code></pre>
<p>上例中我们新声明的 <code>PointInstanceType</code> 类型,与声明 <code>class Point</code> 时创建的 <code>Point</code> 类型是等价的。</p>
<p>所以回到 <code>Point3d</code> 的例子中,我们就能很容易的理解为什么 TypeScript 会支持接口继承类了:</p>
<pre><code class="language-ts">class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
      this.x = x;
      this.y = y;
    }
}

interface PointInstanceType {
    x: number;
    y: number;
}

// 等价于 interface Point3d extends PointInstanceType
interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};
</code></pre>
<p>当我们声明 <code>interface Point3d extends Point</code> 时,<code>Point3d</code> 继承的实际上是类 <code>Point</code> 的实例的类型。</p>
<p>换句话说,可以理解为定义了一个接口 <code>Point3d</code> 继承另一个接口 <code>PointInstanceType</code>。</p>
<p>所以「接口继承类」和「接口继承接口」没有什么本质的区别。</p>
<p>值得注意的是,<code>PointInstanceType</code> 相比于 <code>Point</code>,缺少了 <code>constructor</code> 方法,这是因为声明 <code>Point</code> 类时创建的 <code>Point</code> 类型是不包含构造函数的。另外,除了构造函数是不包含的,静态属性或静态方法也是不包含的(实例的类型当然不应该包括构造函数、静态属性或静态方法)。</p>
<p>换句话说,声明 <code>Point</code> 类时创建的 <code>Point</code> 类型只包含其中的实例属性和实例方法:</p>
<pre><code class="language-ts">class Point {
    /** 静态属性,坐标系原点 */
    static origin = new Point(0, 0);
    /** 静态方法,计算与原点距离 */
    static distanceToOrigin(p: Point) {
      return Math.sqrt(p.x * p.x + p.y * p.y);
    }
    /** 实例属性,x 轴的值 */
    x: number;
    /** 实例属性,y 轴的值 */
    y: number;
    /** 构造函数 */
    constructor(x: number, y: number) {
      this.x = x;
      this.y = y;
    }
    /** 实例方法,打印此点 */
    printPoint() {
      console.log(this.x, this.y);
    }
}

interface PointInstanceType {
    x: number;
    y: number;
    printPoint(): void;
}

let p1: Point;
let p2: PointInstanceType;
</code></pre>
<p>上例中最后的类型 <code>Point</code> 和类型 <code>PointInstanceType</code> 是等价的。</p>
<p>同样的,在接口继承类的时候,也只会继承它的实例属性和实例方法。</p><br><br>
来源:https://www.cnblogs.com/baoshu/p/13620315.html
頁: [1]
查看完整版本: TypeScript学习(二) - TypeScript的接口(interface)和类(class)