ts实战系列十七:type与interface区别

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

(1). 类型区别:

. interface只能表示function、object、class类型:
    interface A {
      name: string;
      add: () => void;
    }
    interface B{
      (): void
    }. type可以表示所有类型:
    type C = () => number;                  // 函数
    type D = string;                        // 字符串
    type E = { name: string, age: number }  // 对象

(2). 名称:

. interface可以合并同名接口:
    interface A{ name: string }
    interface A{ age: number }. type不可以:
    var x:A = { name: 'xx', age: 20 }

(3). 继承:

. interface可以继承interface、继承type(使用extends关键字):. type也可继承type,也可继承interface(使用&). 举例:
    interface A { name: string }
    type C = { sex: string }

    interface B extends A { age: number }        // interface继承interface
    interface D extends C { name: string }       // interface继承type
    type E = { name: string }&C                  // type继承type
    type F = { age: number }&A                   // type继承interface

(4). 实现:

. 类可以实现接口,也可以实现type:. 举例:
    interface A {
      name: string;
      add: () => void
    }
    type B = {
      age: number,
      add: () => void
    }
    class C implements A {
      name: 'xx'
      add() { console.log('类实现接口') }
    }
    class D implements B {
      age: 20
      add() { console.log('类实现type') }
    }

一般,优先用interface来实现,实现不了再用type.

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值