Typescript的本质就是Javasript,只是提供了Javascript目前没有的一些特性.它并不是一门新的编程语言.它和Dart、Cofferscript这些可以转换成Javascript语言是不同的.

Typescript和Javacript最大的不同点就是它的类型系统.围绕类型系统,Typescript提供了:interface和type来声明一个值的类型.

interface和type初看起来没啥区别,官方给的解释是:

Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.

type是给一种类型(原型,方法,对象等)起个别名,interface 是定义一种数据类型.

type和interface功能上没太大的区别,只是在语法上有些不同.

Objects / Functions

它们都可以描述函数和对象类型,只是语法不同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// interface
interface Point {
x: number;
y: number;
}

interface SetPoint {
(x: number, y: number): void;
}

// type alias
type Point = {
x: number;
y: number;
};

type SetPoint = (x: number, y: number) => void;

Other Types

type可以给一种类型,起个别名.interface做不到这个.

1
2
3
4
5
6
7
8
9
10
11
12
// primitive
type Name = string;

// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };

// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];

Extends

interface 和 type支持自身的继承,和互相的继承.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// interface extends interface
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }

//Type alias extends type alias
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };

// Interface extends type alias
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }

// Type alias extends interface
interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };

Implements

class可以实现interface 和 type,它们用法是一样的.但是class 和interface对类型的要求是静止非动态的.联合类型(union)的值是动态的.所以 type定义的 union值 class是无法实现的.

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
interface Point {
x: number;
y: number;
}

class SomePoint implements Point {
x: 1;
y: 2;
}

type Point2 = {
x: number;
y: number;
};

class SomePoint2 implements Point2 {
x: 1;
y: 2;
}

type PartialPoint = { x: number; } | { y: number; };

// FIXME: can not implement a union type
class SomePartialPoint implements PartialPoint {
x: 1;
y: 2;
}

Declaration merging

一个interface可以定义多次,它们值默认是合并的.一个type是不支持多次定义的.

1
2
3
4
5
6
// These two declarations become:
// interface Point { x: number; y: number; }
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };