TypeScript 接口与类型别名的区别

590 阅读2分钟

什么是类型别名(type)

当我们在给值定义类型的时候,使用的方法都是在类型注释中直接定义的 ,这样定义的 对象类型联合类型 固然很方便,但是在我们需要多次使用此类型去定义的时候,难道只能cv吗?

这时就可使用 type 类型别名

上代码!

 type Person = {
        name:string,
        age:number
    }


    let jack : Person = {
        name: 'Jack',
        age:18
    }

    // 此时 jack 的类型指向的就是 Person

    type Id = string|number

    let myID : Id = 123
    let yourID : Id = '123'

    // 这样就可以节省我们的代码数量

什么是接口 (interface)

接口和类型别名类似,接口使用来定义对象的类型的

使用方法:

//一般接口名称都是大写,且不用写等于号
interface Person  {
        name:string,
        age:number
    }

//使用方式与类型一致
 let jack : Person = {
        name: 'Jack',
        age:18
    }

接口与类型别名的区别

接下来具体的讲讲他们的区别

接口与类型别名的扩展(继承)方式不同

接口中,我们可以通过关键字 extends 来继承类型中的字段

// 定义一个类型为动物,字段为名字
    interface Animal {
        name:string
    }
    // 定义一个类型猴子,字段为吃香蕉
    // 且继承动物类型
    interface Monkey extends Animal {
        eatBanana:boolean
    }

    let m : Monkey = {
        name:'吉吉国王',
        eatBanana:true
    }
//这样在 Monkey 类型中也有了name字段

而在 type 中,我们需要通过 & 符号来扩展我们的字段

 // 定义一个类型为动物,字段为名字
    type Animal = {
        name:string
    }
     // 定义一个类型猴子,字段为吃香蕉
    //  并用 & 进行扩展
    type Monkey = {
        eatBanana:boolean
    } & Animal

    let m : Monkey = {
        name:'吉吉国王',
        eatBanana:true
    }

向现有的类型扩展字段

当我们想不改变原来定义的类型,往此类型中继续添加字段的时候推荐使用接口

接口可以重复的定义,而类型别名不可以

接口可以进行一下操作且不会报错

interface Animal {
        name: string
    }
    interface Animal {
        age: number
    }

    let m : Animal = {
        name:'吉吉国王',
        age:18
    }

类型别名就不行了

type Animal = {
        name: string
    }

type Animal = {
        age:number
    }
    
    //在定义的时候就会报错了

感谢阅读!!!