Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

说说TS中type和interface的区别? #88

Open
LuckyWinty opened this issue Jun 10, 2022 · 1 comment
Open

说说TS中type和interface的区别? #88

LuckyWinty opened this issue Jun 10, 2022 · 1 comment

Comments

@LuckyWinty
Copy link
Owner

LuckyWinty commented Jun 10, 2022

type和interface的相同点

在我看来,它俩就是对 接口定义 的两种不同形式,目的都是一样的,都是用来定义 对象 或者 函数 的属性

    interface example {
        name: string
        age: number
    }
    interface exampleFunc {
        (name:string,age:number): void
    }
    
    
    type example = {
        name: string
        age: number
    }
    type example = (name:string,age:number) => v

它俩也支持 继承,并且不是独立的,而是可以 互相 继承,只是具体的形式稍有差别

    type exampleType1 = {
        name: string
    }
    interface exampleInterface1 {
        name: string
    }
    
    
    type exampleType2 = exampleType1 & {
        age: number
    }
    type exampleType2 = exampleInterface1 & {
        age: number
    }
    interface exampleInterface2 extends exampleType1 {
        age: number
    }
    interface exampleInterface2 extends exampleInterface1 {
        age: number
    }

type和interface的不同点

首先聊聊type可以做到,但interface不能做到的事情

  1. type可以定义 基本类型的别名,如 type myString = string
  2. type可以通过 typeof 操作符来定义,如 type myType = typeof someObj
  3. type可以申明 联合类型,如 type unionType = myType1 | myType2
  4. type可以申明 元组类型,如 type yuanzu = [myType1, myType2]

接下来聊聊interface可以做到,但是type不可以做到的事情

  1. interface可以 声明合并
@876843240
Copy link

主要区别有两点
1、type可以声明任意的类型。而interface只能声明对象式的类型
2、type声明只能声明一次。多次声明会出现错误,interface声明的变量可以声明多个。多个interface会基于规则进行合并。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants