TS中类型别名和接口区别

在很多场景下,interface 和 type都能使用,因此两者在很多时候会被混淆:

接口可以通过之间的继承,实现多种接口的组合
使用类型别名也可以实现多种的,通过&连接,有差异:

  • 子接口中不能重新覆盖父接口中的成员,
  • 类型别名会合并,相同类型的成员进行交叉&。若一个number,一个字符串,就无法赋值。如下:
type User1= {
    
    
    name:number,

}
type User2 ={
    
    
    name:string
}

type MyUser = User1 & User2
let user:MyUser ={
    
    
    name:'zdy' 
} 

在这里插入图片描述

交叉平时用的不算很多,接口的继承用的多一些

推荐使用(接口)interface。

1.类型别名

type 会给一个类型起个新名字。 type 有时和 interface 很容易混淆,但是,不同的是,type可以作用于原始值(基本类型),联合类型,元组以及其它任何你需要手写的类型。

起别名不会新建一个类型,它创建了一个新名字来引用那个类型。给基本类型起别名作用不大,但是可以做为文档的一种形式使用.

type Name = string; // 基本类型

type NameFun = () => string; // 函数

type NameOrRFun = Name | NameFun; // 联合类型

function getName(n: NameOrRFun): Name {
    
    
    if (typeof n === 'string') {
    
    
        return n;
    } 
    return n();
}


2.接口

接口使用 interface 关键字进行定义, 在没有设置特殊标识时, 使用接口作为类型定义变量必须将接口内的属性完整定义, 不然就会报错 . 接口定义对象默认属性是可以更改的,接口相当于是一种契约

interface Person {
    
    
  name: string
  age: number
}
const person: Person = {
    
    
  name: 'a',
  age: 1
}
person.age = 2
console.log(person) // {name: 'a', age: 2}

一点小细节:

扫描二维码关注公众号,回复: 17137431 查看本文章

他们在约束函数时候形式有点不大一样,一个是冒号,一个是箭头

// interface
interface SetPoint {
    
    
  (x: number, y: number): void;
}

// type
type SetPoint = (x: number, y: number) => void;

接口和类型别名最大区别:
接口可以被类实现,而类型别名不可以
当然接口也可以继承类,表示类中的所有成员,都在接口中

// 火圈接口
 interface IFireShow{
    
    
    singleFire():void;
    doubleFire():void;
}

// 动物类:
abstract class Animal {
    
    
    abstract type:string;
    constructor(public name:string,public age:number){
    
    

    }
    sayHello(){
    
    
        console.log(`大家好,我是${
      
      this.name},我今年${
      
      this.age}`);
    }
}


class Lion extends Animal implements IFireShow{
    
    
    type:string = "狮子";
    singleFire(){
    
    
        console.log(`${
      
      this.name}我会喷单火圈`);
    }

    doubleFire(){
    
    
        console.log(`${
      
      this.name}我会喷双火圈`);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/134088159