• typeScriptinterface和class区别


    TypeScript中interface和class的区别?

    interface :接口只负责声明成员变量类型,不作具体实现
    class:类既声明成员变量类型并实现

    interface是什么?

    在OOP语言中,接口(interface)是一个很重要的概念,它是对行为的抽象,而具体如何行动需要由类(class)去实现(implement)。

    TypeScript中的接口是一个灵活的概念,除了可用于对类的一部分行为进行抽象之外,也经常使用于对【对象的形状(shape)】进行描述。

     interface Person {
        name: string
        sex: string
        age: number
        getContent():string
      }
      function print(obj:Person):void {
        console.log(obj.getContent())
      }
      print({name: 'll', sex:'male', age: 13, getContent () {return '111'}})
    

    上述的例子是一个简单的interface例子,利用接口约定了传入参数的内容,当不遵照这个约定的时候,typeScript就会报错

    class是什么

    传统方法中,JavaScript竞购构造函数实现类的概念,经过原型链实现继承。而在ES6中,class相当于该实现的语法糖。TypeScript实现了全部ES6中的类的功能之外,还外加了一些新的方法。(这里只说明interface和class的区别)。

    class Person_1 {
        public name: string = 'dd'
        public sex:string = 'male'
        public age:number = 29
        constructor (obj: Person) {
          this.name = obj.name
          this.age = obj.age
          this.sex = obj.sex
        }
        say(message: string) {
          return `my name is ${this.name}, I'm ${this.age} years old, I'm a ${this.sex === 'male' ? 'boy' : 'girl'},  ${message}`
        }
      }
      const person_1 = new Person_1({name: 'ddd', age: 29, sex:'male',getContent () {return '222'}})
      console.log(person_1)
      console.log(person_1.say('hello world'))
    

    接口继承类

      interface Person1 extends Person_1 {
        printName() : void
      }
      const person1:Person1 = {
        name: 'sss',
        sex: 'male',
        age: 29,
        say (message: string): string {
          return 'dddd'
        },
        printName () {}
      } 
      console.log(person1)
    

    类实现接口

      class Person2 implements Person1 {
        name: string
        age: number
        sex: string
        printName()  {
          console.log('111')
        }
        say(message: string): string {
          console.log('ddd',message)
          return  `ddd${message}`
        }
      }
    

    总结

    TypeScript中声明class,实际上,除了会建立一个类以外,同时也会建立一个同名的interface(同名的interface只包含其中的实例属性和实例方法)。因此class既能够看成类来使用,也能够看成interface来使用。

  • 相关阅读:
    四、网络层
    四、路由协议
    四、最长前缀匹配
    四、路由转发
    四、分片
    五、TCP的可靠传输你怎么看
    存储周期
    判断素数
    需求说明书的内容
    块级元素——盒子模型1
  • 原文地址:https://www.cnblogs.com/dehenliu/p/16072856.html
Copyright © 2020-2023  润新知