What’s the differences between interface and type in typescript.
types can create primitive type alias, while interface cannot.
1
2type Name = string;
const name: Name = 'zdd';interface can do declaration merging together
1
2
3
4
5
6
7
8
9
10
11
12
13
14interface Person {
name: string;
}
interface Person {
age: number;
}
const person: Person = {
name: 'zdd',
age: 18
}
console.log(person);while type can not do declaration merging
1
2
3
4
5
6
7
8
9
10
11
12type Person = {
name: string;
}
type Person = { // Error, Duplicate identifier 'Person'
age: number;
}
const person: Person = {
name: 'zdd',
age: 18,
}Extends and implements
- interface can extends another interface or class
- class can implement interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Person {
sayHi() {
console.log('Hi')
}
}
interface IPerson extends Person {
name: string;
}
class Student implements IPerson {
name: string;
constructor(name: string) {
this.name = name;
}
sayHi() {
console.log('Hi, I am a student')
}
}Interface extends interface
1
2
3interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }Type alias extends type alias
1
2type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };Interface extends type alias
1
2type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }Type alias extends interface
1
2interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };types can create
interaction
types, but interface not.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20type Name = {
name: string;
}
type Age = {
age: number;
}
type Person = Name & Age; // OK
interface Name {
name: string;
}
interface Age {
age: string;
}
type Person = Name & Age; // OK
interface Person = Name & Age // Error.types can create
union
types, but interface not.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20type Man = {
name: string;
}
type Women = {
name: string;
}
type Person = Man | Women; // ok
interface Man {
name: string;
}
interface Woman {
name: string;
}
type Person = Man & Woman; // ok
interface Person = Man & Woman; // Error.types can define
tuple
, but interface not.1
2type Response = [string, number]; // ok
interface Response = [string, number]; // not work
总结一下,主要的区别就是:
interface
可以做declaration合并,但是type不能。interface
can be extend byclass
, while type can not be extend.type
可以定义union
interaction
类型,但是interface
不能。