1.1 typescript中的interface

一、java中的interface

java

1、interface中的除非静态、非default方法都是抽象方法,只有定义,没有实现

2、interface中的变量都是常量,被final static修饰

3、interface中可以有default方法,可以有实现,可以被interface的子类引用调用

4、interface中可以有静态方法及实现,可以通过类名直接调用

5、方法及成员都是被public修饰的

6、interface之间才能使用extends,class和interface之间只能使用implement

public interface A {
    default int hello(){
        return 1;
    }
     String name = "test";
     void get();
     void set();
     static void say() {
         System.out.println("say method");
     };
     int num = 1;
}

typescript

1、interface中的属性和方法不需要修饰符修饰,方法不需要实现,但是要标明返回值

2、interface的属性需要标明属性的数据类型

3、interface中的属性可以是一个赋值为具体的值,实现后也可以更改,ts会报类型错误,需要使用// @ts-ignore忽略错误

4、interface的名称是一个引用类型,不能使用new B() instanceof A这种形式,但是可以用做类型检查

5、interface之间才能使用extends,class和interface之间只能使用implement

interface A{
     name: string,
     age: 1,
     say(): void
     hello(): void
}
class B implements A{
     name = '1';
     // @ts-ignore   使用ignore忽略报错
     age = 2;
     say(): void {
     }
}
class C{
     get(name: A){ //类型检查
     }
}
new C().get('11')//A当作类型检查使用
console.log(new B().name)//
console.log(new B().age)
// new B() instanceof A 不可以这样使用

typescript中的interface如果没有实现,tsc编译后是啥都没有,即便有实现,编译产生的自执行function也是依据class的实现类,所以interface只是typescript语言的语法糖,抽象类也是一样,即便不用interface,也可以用抽象类的方式,实现相同的效果,因此interface是在typescript层面用来做一些属性拼装后的特定类型检查,也可以提供公共的方法,供class去实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值