different between interface and type of typescript

An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.

An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

相同点

都可以描述一个对象或者函数

interface

1
2
3
4
5
6
7
8
9
10
11
interface User {
name: string
age: number
}
interface UserApi {
(name: string, age: number):void
}
var user:User = {name: '1', age: 1}
var func: UserApi = (name: string, age: number) => void {

}

type

1
2
3
4
5
6
7
type User = {
name: string
age: number
}
type SetUser = (name: string, age: number) => void
var user:User = {name: '1', age: 1}
var serUser: SetUser = (name: string, age: number) => void {}

都允许拓展(extends)

interface extends interface

1
2
3
4
5
6
7
8
9
10
11
12
interface Base {
name: string;
}
interface Child extends Base{
setName(name: string): void
}
var a:Child = {
name: '1',
setName(name: string) {
console.log(name)
}
}

type extends type

1
2
3
4
5
type User = {
name: string;
}
type NewType = User & {age: number}
var aa:NewType = {name: '1', age:2}

interface extends type

1
2
3
4
5
6
7
type Name = {
name: string;
}
interface User extends Name {
age: number
}
var user:User = {name: '1', age:1}

type extends interface

1
2
3
4
5
interface Name {
name: string
}
type User = Name & {age: number}
var user:User = {name: '1', age: 1}

不同点

type 可以而 interface 不行

type 可以声明基本类型别名,联合类型,元组等类型

基本类型

1
type Name: string

联合类型

1
2
3
4
5
6
7
8
9
interface A {
name: string
}
interface B {
age: number
}
type User = A & B
var user:User = {name: '1', age:1}
type Name: string

元组

1
2
type arr = [number, string, boolean]
var a:arr = [1,'1',true]

type 语句中还可以使用 typeof 获取实例的 类型进行赋值

1
type UserType = typeof User

interface 可以而 type 不行

interface 能够声明合并

1
2
3
4
5
6
7
interface User {
name: string
}
interface User {
age: number
}
var user: User = {name: '1', age: 1}

一般来说,如果不清楚什么时候用interface/type,能用 interface 实现,就用 interface , 如果不能就用 type

Author: Rick
Link: https://rcrick.github.io/2020/04/06/different-between-interface-and-type-of-typescript/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶