typescript中interface和type的使用

interface(接口)

声明对象或者函数,通过extends继承拓展

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
// 描述对象
interface IUser {
name: string,
age: number,
sayHi: () => void
// sayHi(): void
}

const user: IUser = {
name: 'zhangsan',
age: 25,
sayHi: () => {
console.log('hi, i am zhangsan')
}
}
user.sayHi();

// 描述函数
interface ISetUser {
(name: string, age: number, sayHi: () => void): void;
}

const setUser: ISetUser = (name: string, age: number, sayHi: () => void) => {
user.name = name;
user.age = age;
user.sayHi = sayHi;
}

setUser('lisi', 30, () => { console.log('hi, i am lisi') });
user.sayHi();

// IMaleUser继承IUser
interface IMaleUser extends IUser {
gender: string
}

let maleUser: IMaleUser = {
name: 'lilei',
age: 20,
gender: '男',
sayHi: () => {
console.log('hi, i am lilei')
}
}
maleUser.sayHi();

// 运行结果
// hi, i am zhangsan
// hi, i am lisi
// hi, i am lilei

type(类型别名)

声明对象或者函数,通过&来扩展

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
// 描述对象
type IUser = {
name: string,
age: number,
sayHi: () => void
// sayHi(): void
}

const user: IUser = {
name: 'zhangsan',
age: 25,
sayHi: () => {
console.log('hi, i am zhangsan')
}
}
user.sayHi();

// 描述函数
type ISetUser = {
(name: string, age: number, sayHi: () => void): void;
}

const setUser: ISetUser = (name: string, age: number, sayHi: () => void) => {
user.name = name;
user.age = age;
user.sayHi = sayHi;
}

setUser('lisi', 30, () => { console.log('hi, i am lisi') });
user.sayHi();

// IMaleUser继承IUser
type IMaleUser = IUser & {
gender: string
}

let maleUser: IMaleUser = {
name: 'lilei',
age: 20,
gender: '男',
sayHi: () => {
console.log('hi, i am lilei')
}
}
maleUser.sayHi();

// 运行结果
// hi, i am zhangsan
// hi, i am lisi
// hi, i am lilei

声明基本类型别名、联合类型、元组等类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 基本类型
type id = number

// 联合类型
type Dog = {
name: string
}
type Cat = {
name: number
}
type Pet = Dog | Cat;
let it1: Pet = {
name: 'dahuang'
}
let it2: Pet = {
name: 9527
}
console.log(it1.name); // dahuang
console.log(it2.name); // 9527

// 元组
type PetList = [Dog, Pet];
let its: PetList = [{ name: 'xiaohuang' }, it1];
console.log(its); // [ { name: 'xiaohuang' }, { name: 'dahuang' } ]

总结

相同点:都可以声明对象或者函数,二者都可以交叉互相继承。

不同点:

  1. type可以声明更多类型,基本类型别名、联合类型、元组等;
  2. interface可以合并同名声明。