typeScript-interface和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来使用。

posted @ 2022-03-29 17:14  upupupupupgo  阅读(510)  评论(0编辑  收藏  举报