Gowhich

Durban's Blog

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.1.1

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node 脚本路径

公共,私有与受保护的修饰符

默认为 public

在上篇文章【TypeScript基础入门 - 类 - 继承】的例子里,我们可以自由的访问程序里定义的成员。 如果你对其它语言中的类比较了解,就会注意到我们在之前的代码里并没有使用 public来做修饰;例如,C#要求必须明确地使用 public指定成员是可见的。 在TypeScript里,成员都默认为public。你也可以明确的将一个成员标记成public。 我们可以用下面的方式来实现一个Animal类:

1
2
3
4
5
6
7
8
9
10
class Animal {
public name: string;
public constructor(theColor: string) {
this.name = theColor;
}

public move(distanceMeter: number = 0) {
console.log(`${this.name} moved ${distanceMeter}m`);
}
}

理解 private

当成员被标记成 private时,它就不能在声明它的类的外部访问。比如:

1
2
3
4
5
6
7
8
9
10
11
12
class Animal {
private name: string;
public constructor(theName: string) {
this.name = theName;
}

public move(distanceMeter: number = 0) {
console.log(`${this.name} moved ${distanceMeter}m`);
}
}

new Animal('small cat').name;

运行后得到如下结果

1
2
3
$ npx ts-node src/classes_3.ts
⨯ Unable to compile TypeScript:
src/classes_3.ts(12,25): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

TypeScript使用的是结构性类型系统。 当我们比较两种不同的类型时,并不在乎它们从何处而来,如果所有成员的类型都是兼容的,我们就认为它们的类型是兼容的。

然而,当我们比较带有 private或 protected成员的类型的时候,情况就不同了。 如果其中一个类型里包含一个 private成员,那么只有当另外一个类型中也存在这样一个 private成员, 并且它们都是来自同一处声明时,我们才认为这两个类型是兼容的。 对于 protected成员也使用这个规则。下面来看一个例子,更好地说明了这一点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Animal {
private name: string;
public constructor(theName: string) {
this.name = theName;
}

public move(distanceMeter: number = 0) {
console.log(`${this.name} moved ${distanceMeter}m`);
}
}

class Dog extends Animal {
constructor(name: string) {
super(name);
}
}

class Person {
private name: string;

public constructor(theName: string) {
this.name = theName;
}

public move(distanceMeter: number = 0) {
console.log(`${this.name} moved ${distanceMeter}m`);
}
}

let animal = new Animal('animal');
let dog = new Dog('dog');
let person = new Person('person');

animal = dog
animal = person;

运行后得到如下结果

1
2
3
4
$ npx ts-node src/classes_3.ts
⨯ Unable to compile TypeScript:
src/classes_3.ts(35,1): error TS2322: Type 'Person' is not assignable to type 'Animal'.
Types have separate declarations of a private property 'name'.

这个例子中有Animal和Dog两个类, Dog是 Animal类的子类。还有一个Person类,其类型看上去与Animal是相同的。 我们创建了几个这些类的实例,并相互赋值来看看会发生什么。因为Animal和Dog共享了来自Animal里的私有成员定义private name: string,因此它们是兼容的。 然而 Person却不是这样。当把Person赋值给Animal的时候,得到一个错误,说它们的类型不兼容。尽管Person里也有一个私有成员name,但它明显不是Animal里面定义的那个。

理解 protected

protected修饰符与 private修饰符的行为很相似,但有一点不同, protected成员在派生类中仍然可以访问。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}

class Employee extends Person {
private department: string;

constructor(name: string, department: string) {
super(name);
this.department = department;
}

getWorkInfo() {
return `我叫${this.name},我工作在${this.department}`;
}
}

let aEmployee = new Employee('durban', '华盛顿');
console.log(aEmployee.getWorkInfo());
console.log(aEmployee.name);

运行后得到的结果如下

1
2
3
$ npx ts-node src/classes_3.ts
⨯ Unable to compile TypeScript:
src/classes_3.ts(23,23): error TS2445: Property 'name' is protected and only accessible within class 'Person' and its subclasses.

注意,我们不能在 Person类外使用 name,但是我们仍然可以通过 Employee类的实例方法访问,因为 Employee是由 Person派生而来的。构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Person {
protected name: string;
protected constructor(name: string) {
this.name = name;
}
}

class Employee extends Person {
private department: string;

constructor(name: string, department: string) {
super(name);
this.department = department;
}

getWorkInfo() {
return `我叫${this.name},我工作在${this.department}`;
}
}

let aEmployee = new Employee('durban', '华盛顿');
let aPerson = new Person('Sakuro');

运行后得到如下错误

1
2
3
$ npx ts-node src/classes_3.ts
⨯ Unable to compile TypeScript:
src/classes_3.ts(22,15): error TS2674: Constructor of class 'Person' is protected and only accessible within the class declaration.

readonly修饰符

你可以使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。如下:

1
2
3
4
5
6
7
8
9
class Person {
readonly name: string;
constructor(name: string) {
this.name = name;
}
}

const aPerson = new Person('Xiaowang');
aPerson.name = 'Xiaoli';

运行后得到如下

1
2
3
$ npx ts-node src/classes_3.ts
⨯ Unable to compile TypeScript:
src/classes_3.ts(9,9): error TS2540: Cannot assign to 'name' because it is a constant or a read-only property.

参数属性

在上面的例子中,我们不得不定义一个受保护的成员 name和一个构造函数参数 theName在 Person类里,并且立刻给 name和 theName赋值。 这种情况经常会遇到。 参数属性可以方便地让我们在一个地方定义并初始化一个成员。 下面的例子是对之前 Animal类的修改版,使用了参数属性:

1
2
3
4
5
6
7
class Animal {
public constructor(private name: string) { }

public move(distanceMeter: number = 0) {
console.log(`${this.name} moved ${distanceMeter}m`);
}
}

注意看我们是如何舍弃了 theName,仅在构造函数里使用 private name: string参数来创建和初始化 name成员。 我们把声明和赋值合并至一处。

参数属性通过给构造函数参数添加一个访问限定符来声明。 使用 private限定一个参数属性会声明并初始化一个私有成员;对于 public和 protected来说也是一样。

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.1.2

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.1.0

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node 脚本路径

继承

在TypeScript里,我们可以使用常用的面向对象模式。 基于类的程序设计中一种最基本的模式是允许使用继承来扩展现有的类。看下面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Animal {
move(distanceMeter: number = 0) {
console.log(`Animal moved ${distanceMeter}m`);
}
}

class Dog extends Animal {
bark() {
console.log('Woof........!');
}
}

const dog = new Dog();
dog.bark();
dog.move(3);
dog.bark();

运行后得到如下结果

1
2
3
4
$ npx ts-node src/classes_2.ts
Woof........!
Animal moved 3m
Woof........!

这个例子展示了最基本的继承:类从基类中继承了属性和方法。这里,Dog是一个派生类,它派生自Animal基类,通过extends关键字。派生类通常被称作 子类,基类通常被称作超类。

因为Dog继承了Animal的功能,因此我们可以创建一个Dog的实例,它能够 bark()和move()。下面我们来看个更加复杂的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}

move(distanceMeter: number = 0) {
console.log(`${this.name} moved ${distanceMeter}m`);
}
}

class Snake extends Animal {
constructor(name: string) {
super(name);
}

move(distanceMeter: number = 5) {
console.log('滑动的声音......');
super.move(distanceMeter);
}
}

class Horse extends Animal {
constructor(name: string) {
super(name);
}

move(distanceMeter: number = 45) {
console.log('跑动的声音......');
super.move(distanceMeter);
}
}

const snake = new Snake('small snake');
const horse: Animal = new Horse('small horse');

snake.move();
horse.move(152);

运行后得到如下结果

1
2
3
4
5
$ npx ts-node src/classes_2.ts
滑动的声音......
small snake moved 5m
跑动的声音......
small horse moved 152m

这个例子展示了一些上篇文章【TypeScript基础入门 - 类 - 简介】没有提到的特性。 这一次,我们使用extends关键字创建了 Animal的两个子类:Horse和 Snake。

与前一个例子的不同点是,派生类包含了一个构造函数,它必须调用super(),它会执行基类的构造函数。 而且,在构造函数里访问this的属性之前,我们一定要调用 super()。 这个是TypeScript强制执行的一条重要规则。

这个例子演示了如何在子类里可以重写父类的方法。Snake类和 Horse类都创建了move方法,它们重写了从Animal继承来的move方法,使得 move方法根据不同的类而具有不同的功能。注意,即使horse被声明为Animal类型,但因为它的值是Horse,调用tom.move(152)时,它会调用Horse里重写的方法。

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.1.1

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.14

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node 脚本路径

介绍

传统的JavaScript程序使用函数和基于原型的继承来创建可重用的组件,但对于熟悉使用面向对象方式的程序员来讲就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。 从ECMAScript 2015,也就是ECMAScript 6开始,JavaScript程序员将能够使用基于类的面向对象的方式。 使用TypeScript,我们允许开发者现在就使用这些特性,并且编译后的JavaScript可以在所有主流浏览器和平台上运行,而不需要等到下个JavaScript版本。

类的使用

下面看一个使用类的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}

greet() {
return this.greeting;
}
}

const greeter = new Greeter("Good Morning");
console.log(greeter.greet());

运行后得到如下结果

1
2
$ npx ts-node src/classes_1.ts
Good Morning

如果你使用过C#或Java,你会对这种语法非常熟悉。 我们声明一个 Greeter类。这个类有3个成员:一个叫做 greeting的属性,一个构造函数和一个 greet方法。

你会注意到,我们在引用任何一个类成员的时候都用了 this。 它表示我们访问的是类的成员。

最后一行,我们使用 new构造了 Greeter类的一个实例。 它会调用之前定义的构造函数,创建一个 Greeter类型的新对象,并执行构造函数初始化它。

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.1.0

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.13

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node src/learn_basic_types.ts
1
npx ts-node 脚本路径

接口

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

继承接口

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

1
2
3
4
5
6
7
8
9
10
11
interface Shape {
color: string;
}

interface Square extends Shape {
sideLength: number;
}

let square = <Square> {};
square.color = 'red'
square.sideLength = 10;

一个接口可以继承多个接口,创建出多个接口的合成接口。如下实例演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface Shape {
color: string;
}

interface PenStroke {
penWidth: number;
}

interface Square extends Shape, PenStroke {
sideLength: number;
}

let square = <Square> {};
square.color = 'red'
square.sideLength = 10;
square.penWidth = 10;

混合类型

先前我们提过,接口能够描述JavaScript里丰富的类型。 因为JavaScript其动态灵活的特点,有时你会希望一个对象可以同时具有上面提到的多种类型。一个例子就是,一个对象可以同时做为函数和对象使用,并带有额外的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface Counter {
(start: number): string
interval: number;
reset(): void;
}

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

let counter = getCounter()
counter(10);
counter.reset();
counter.interval = 10.0

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

接口继承类

当接口继承了一个类类型时,它会继承类的成员但不包括其实现。 就好像接口声明了所有类中存在的成员,但并没有提供具体实现一样。 接口同样会继承到类的private和protected成员。 这意味着当你创建了一个接口继承了一个拥有私有或受保护的成员的类时,这个接口类型只能被这个类或其子类所实现(implement)。当你有一个庞大的继承结构时这很有用,但要指出的是你的代码只在子类拥有特定属性时起作用。 这个子类除了继承至基类外与基类没有任何关系。 例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Control {
private state: any;
}

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

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

class TextBox extends Control {

}

class Image implements SelectableControl {
select() {}
}

运行后会爆出如下异常

1
2
3
4
⨯ Unable to compile TypeScript:
src/interface_8.ts(54,7): error TS2300: Duplicate identifier 'Image'.
src/interface_8.ts(54,7): error TS2420: Class 'Image' incorrectly implements interface 'SelectableControl'.
Property 'state' is missing in type 'Image'.

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

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

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.14

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.12

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node src/learn_basic_types.ts
1
npx ts-node 脚本路径

接口

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

类类型

实现接口

与C#或Java里接口的基本作用一样,TypeScript也能够用它来明确的强制一个类去符合某种契约。如下实现

1
2
3
4
5
6
7
8
interface SomeClassInterface {
property1: string;
}

class implementSomeInterface implements SomeClassInterface {
property1: string;
constructor(arg1: number, arg2: number) {}
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
interface SomeClassInterface {
property1: string;
// 设置property1
setProperty1(p: string): any;
}

class implementSomeInterface implements SomeClassInterface {
property1: string;
constructor(arg1: number, arg2: number) {}
setProperty1(p: string): any {
this.property1 = p;
}
}

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

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

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

1
2
3
4
5
6
7
8
interface SomeConstructor {
new (arg1: string, arg2: string): any
}

class SomeClass implements SomeConstructor {
property1: string;
constructor(arg1: string, arg2: string) {}
}

运行后报错误如下

1
2
3
⨯ Unable to compile TypeScript:
src/interface_7.ts(20,7): error TS2420: Class 'SomeClass' incorrectly implements interface 'SomeConstructor'.
Type 'SomeClass' provides no match for the signature 'new (arg1: string, arg2: string): any'.

这里因为当一个类实现了一个接口时,只对其实例部分进行类型检查。 constructor存在于类的静态部分,所以不在检查的范围内。因此,我们应该直接操作类的静态部分。 看下面的例子,我们定义了两个接口,SomeConstructor为构造函数所用和SomeClassInterface为实例方法所用。 为了方便我们定义一个构造函数createSomeFunc,它用传入的类型创建实例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
interface SomeClassInterface {
property1: string;
// 设置property1
setProperty1(p: string): any;
getProperty1(): string;
}

interface SomeConstructor {
new(arg1: string, arg2: string): SomeClassInterface
}

function createSomeFunc(ctr: SomeConstructor, arg1: string, arg2: string): SomeClassInterface {
return new ctr(arg1, arg2)
}

class ImplementSomeInterface1 implements SomeClassInterface {
property1: string;
property2: string;
constructor(arg1: string, arg2: string) {
this.property1 = arg1;
this.property2 = arg2;
}
setProperty1(p: string): any {
this.property1 = p;
}

getProperty1() {
return this.property1 + ' = implementSomeInterface1';
}
}

class ImplementSomeInterface2 implements SomeClassInterface {
property1: string;
property2: string;
constructor(arg1: string, arg2: string) {
this.property1 = arg1;
this.property2 = arg2;
}
setProperty1(p: string): any {
this.property1 = p;
}

getProperty1() {
return this.property1 + ' = implementSomeInterface2';
}
}

let instance1 = createSomeFunc(ImplementSomeInterface1, 'arg1', 'arg2');
let instance2 = createSomeFunc(ImplementSomeInterface2, 'arg1', 'arg2');
console.log(instance1.getProperty1());
console.log(instance2.getProperty1());

运行后得到的结果如下

1
2
arg1 = implementSomeInterface1
arg1 = implementSomeInterface2

因为createSomeFunc的第一个参数是SomeConstructor类型,在createSomeFunc(ImplementSomeInterface1, ‘arg1’, ‘arg2’)里,会检查ImplementSomeInterface1是否符合构造函数签名。

我觉得这里的话官方写的有点复杂了,为什么一定要使用一个构造函数接口呢,比如下面

1
2
let instance3 = new ImplementSomeInterface2('arg1','arg2')
console.log(instance3.getProperty1());

一样可以实现实例化,并且调用方法函数

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.13

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.11

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node src/learn_basic_types.ts
1
npx ts-node 脚本路径

接口

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

可索引的类型

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

1
2
3
4
5
6
7
8
9
interface SomeArray {
[index: number]: string;
}

let someArray: SomeArray;
someArray = ["string1", "string2"];

let str: string = someArray[0];
console.log(str);

运行后结果如下

1
string1

上面例子里,我们定义了SomeArray接口,它具有索引签名。 这个索引签名表示了当用 number去索引SomeArray时会得到string类型的返回值。共有支持两种索引签名:字符串和数字。 可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用 number来索引时,JavaScript会将它转换成string然后再去索引对象。 也就是说用 100(一个number)去索引等同于使用”100”(一个string)去索引,因此两者需要保持一致。

1
2
3
4
5
6
7
8
9
10
11
12
class Person {
name: string;
}
class Student extends Person {
className: string;
}

// 错误:使用数值型的字符串索引,有时会得到完全不同的Person!
interface NotOkay {
// [x: number]: Person; // 数字索引类型“Person”不能赋给字符串索引类型“Student”
[x: string]: Student;
}

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

1
2
3
4
5
interface SomeInterface {
[index: string]: string
// length: number // 错误,`length`的类型与索引类型返回值的类型不匹配
name: string // 可以,name是string类型
}

最后,你可以将索引签名设置为只读,这样就防止了给索引赋值:

1
2
3
4
5
6
7
8
9
10
11
interface SomeInterface {
[index: string]: string
// length: number // 错误,`length`的类型与索引类型返回值的类型不匹配
name: string // 可以,name是string类型
}

interface ReadonlySomeArray {
readonly [index: number]: string;
}
let readonlyArray: ReadonlySomeArray = ["string1", "string2"];
readonlyArray[2] = "string3"; // error!

运行后会得到如下错误提示

1
src/interface_6.ts(36,1): error TS2542: Index signature in type 'ReadonlySomeArray' only permits reading.

你不能设置readonlyArray[2],因为索引签名是只读的。

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.12

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.10

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node src/learn_basic_types.ts
1
npx ts-node 脚本路径

接口

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

函数类型

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

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

1
2
3
interface SomeInterface {
(arg1: string, arg2: string): boolean;
}

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

1
2
3
4
5
6
let someFunc: SomeInterface
someFunc = function (arg1: string, arg2: string) {
const res = arg1.search(arg2)
return res > -1;
}
console.log(someFunc('weast','east'));

运行后得到的结果如下

1
true

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

1
2
3
4
5
6
let someFunc2: SomeInterface;
someFunc2 = function (x: string, y: string): boolean {
const res = x.search(y);
return res > -1;
}
console.log(someFunc2('weast', 'east'));

运行后得到的结果如下

1
true

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

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.11

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.9

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node src/learn_basic_types.ts
1
npx ts-node 脚本路径

接口

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

额外的属性检查

首先看一个示例,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface SquareConfig {
color?: string;
width?: number;
}

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

let mySquare = createSquare({ colour: "red", width: 100 });

运行后接到的结果如下

1
2
3
⨯ Unable to compile TypeScript:
src/interface_4.ts(17,31): error TS2345: Argument of type '{ colour: string; width: number; }' is not assignable to parameter of type 'SquareConfig'.
Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?

如果看过前面的文章的话,上面的代码应该会很容易理解。注意传入createSquare的参数拼写为colour而不是color。 在JavaScript里,这会默默地失败。

你可能会争辩这个程序已经正确地类型化了,因为width属性是兼容的,不存在color属性,而且额外的colour属性是无意义的。

然而,TypeScript会认为这段代码可能存在bug。 对象字面量会被特殊对待而且会经过”额外属性检查”,当将它们赋值给变量或作为参数传递的时候。 如果一个对象字面量存在任何”目标类型”不包含的属性时,你会得到一个错误。

1
2
// error: 'colour' not expected in type 'SquareConfig'
let mySquare = createSquare({ colour: "red", width: 100 });

绕开这些检查非常简单。 最简便的方法是使用类型断言:

1
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

然而,最佳的方式是能够添加一个字符串索引签名,前提是你能够确定这个对象可能具有某些做为特殊用途使用的额外属性。 如果 SquareConfig带有上面定义的类型的color和width属性,并且还会带有任意数量的其它属性,那么我们可以这样定义它:

1
2
3
4
5
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}

后面会分享到索引签名,但在这我们要表示的是SquareConfig可以有任意数量的属性,并且只要它们不是color和width,那么就无所谓它们的类型是什么。

还有最后一种跳过这些检查的方式,这可能会让你感到惊讶,它就是将这个对象赋值给一个另一个变量: 因为 squareOptions不会经过额外属性检查,所以编译器不会报错。

1
2
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);

要留意,在像上面一样的简单代码里,你可能不应该去绕开这些检查。 对于包含方法和内部状态的复杂对象字面量来讲,你可能需要使用这些技巧,但是大部额外属性检查错误是真正的bug。 就是说你遇到了额外类型检查出的错误,比如“option bags”,你应该去审查一下你的类型声明。 在这里,如果支持传入 color或colour属性到createSquare,你应该修改SquareConfig定义来体现出这一点。

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.10

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.8

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node src/learn_basic_types.ts
1
npx ts-node 脚本路径

接口

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

只读属性

一些对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 readonly来指定只读属性:

1
2
3
4
interface Point {
readonly x: number;
readonly y: number;
}

你可以通过赋值一个对象字面量来构造一个Point。 赋值后, x和y再也不能被改变了。

1
2
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!

运行后得到如下结果

1
2
⨯ Unable to compile TypeScript:
src/interface_3.ts(7,4): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property.

TypeScript具有ReadonlyArray类型,它与Array相似,只是把所有可变方法去掉了,因此可以确保数组创建后再也不能被修改:

1
2
3
4
5
6
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
2
3
4
5
6
⨯ Unable to compile TypeScript:
src/interface_3.ts(11,1): error TS2542: Index signature in type 'ReadonlyArray<number>' only permits reading.
src/interface_3.ts(12,4): error TS2339: Property 'push' does not exist on type 'ReadonlyArray<number>'.
src/interface_3.ts(13,4): error TS2540: Cannot assign to 'length' because it is a constant or a read-only property.
src/interface_3.ts(14,1): error TS2322: Type 'ReadonlyArray<number>' is not assignable to type 'number[]'.
Property 'push' is missing in type 'ReadonlyArray<number>'.

上面代码的最后一行,可以看到就算把整个ReadonlyArray赋值到一个普通数组也是不可以的。 但是你可以用类型断言重写:

1
2
3
4
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
a = ro as number[];
console.log(a);

运行后得到的结果如下

1
[ 1, 2, 3, 4 ]

readonly vs const

最简单判断该用readonly还是const的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 const,若做为属性则使用readonly。

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.9

项目实践仓库

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.7

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

1
npm install -D ts-node

后面自己在练习的时候可以这样使用

1
npx ts-node src/learn_basic_types.ts
1
npx ts-node 脚本路径

接口

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

可选属性

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface SquareConfig {
color?: string;
width?: number;
}

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

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

运行后结果如下

1
{ color: 'black', area: 100 }

带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?符号。可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误。 比如,我们故意将 createSquare里的color属性名拼错,就会得到一个错误提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}

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

运行后结果如下

1
2
3
⨯ Unable to compile TypeScript:
src/interface_2.ts(27,16): error TS2551: Property 'clor' does not exist on type 'SquareConfig'. Did you mean 'color'?
src/interface_2.ts(29,34): error TS2551: Property 'clor' does not exist on type 'SquareConfig'. Did you mean 'color'?

本实例结束实践项目地址

1
2
https://github.com/durban89/typescript_demo.git
tag: 1.0.8
0%