TS中type与interface

interface与type的定义和作用 

interface主要用于类型的检查,定义具有相似类型的名称和类型的对象结构。此外也可定义方法和事件,可以被多次定义,还可以被implement实现

type还可定义基础类型、联合类型或交叉类型,只能定义一次

区别

1. 定义范围不同

interface只能定义对象
type可定义基础类型、联合类型和交叉类型

// 接口的基本使用
interface student {
    name: string,
    age: number
}
const t:student = {
    name:'ddd',
    age:50
} 
// 类型的基本使用
type studentType = {
    name:string,
    age:number
}
const n:studentType = {
    name:'sea',
    age:20
}
// 类型定义元组
type a = [string,number]
const m:a = ['sss', 999]
// 联合类型
interface apple {
    name:string
}
interface banana {
    name:string
}
type c = apple | banana
type d = c & apple
const s:d = {
    name:'水果'
}

2. 可扩展性

接口interface可extends、implements,具有较高的拓展性

extends

interface apple {
    name:string
}
// 接口继承
interface appleInfo extends apple {
    year:number
}
const aApple:appleInfo = {
    year:1,
    name:'sss'
}

implements

// 定义公共方法,具体实现在对应的类中实现
interface publicFun {
    name():string|number
    log(): void
}
// 方法的实现
class showWarn implements publicFun {
    name(){
        return 'warn'
    }
    log() {
        console.log('warn')
    }
}
class showSuccess implements publicFun {
    name(){
        return 45
    }
    log() {
        console.log('success')
    }
}
// extends与implement同时使用
class show extends showSuccess implements publicFun {
}
const ss = new show()
console.log(ss.name()) // 45

type可使用交叉类型&合并不同的type或interface

interface apple {
    color: string
    name: string
}
interface banana {
    name: string
}
// 合并两个interface
type fruit= banana & apple
const f: fruit = {
    name: '水果',
    color: 'red'
}
type obj1 = {
    name:string
}
type obj2 = {
    age:number
}
// 合并两个type
type obj3 = obj1 & obj2
const arr:obj3 = {
    name: '姓名',
    age: 54
}
// 合并type与interface
type merge = obj1 & apple
const na:merge = {
    color: 'red',
    name:'名字',
}

3.同名定义

interface定义存在同名定义时,会合并两个interface

interface apple {
    color: string
}
interface apple {
    name: string
}
// 同名接口会直接合并
const appleName:apple = {
    color:'red',
    name:'apple'
}

type定义存在同名定义时,会抛出错误

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/130342476
今日推荐