【问题标题】:TypeScript why use traditional classes instead of interfaces?TypeScript 为什么使用传统的类而不是接口?
【发布时间】:2021-12-05 01:20:12
【问题描述】:

我可以这样做:

enum DogsKinds {
  Labrador,
  Aski
}

class Dog {
  name: string;
  kind: DogKinds;
  constructor() {}
}

然后初始化一个狗对象:

const dog = new Dog();

但是我可以对界面做同样的事情:

interface Dog {
  name: string;
  kind: DogsKind;
}

const dog: Dog = {
  name: 'some name',
  kind: DogsKinds.Labrador
}

并获得相同的结果 - 更容易。

有什么区别,何时使用接口和何时使用类,是否有最佳实践或经验法则?

界面似乎更容易使用,如果我错了请纠正我。

【问题讨论】:

  • 您也可以在可能的情况下完全省略两者(就像我喜欢的那样),并使用纯对象文字和推断类型。
  • 但是以后不能再用了
  • @Raz 您的演示代码也没有显示重用示例。尝试添加它,构造函数的优势应该会变得更加明显
  • 顺便说一句,您需要修复“属性'name'没有初始化器,并且没有在构造函数中明确分配。属性'kind'没有初始化器,也没有明确分配在构造函数。”编译器吐出的错误
  • 请注意,在 TypeScript 中,每个 class 声明都会声明一个接口(一种类型)并定义一个 class 对象。

标签: javascript typescript class oop interface


【解决方案1】:

我认为一个重要的区别是在运行时找出您在使用继承时处理的对象类型

对于类,您可以使用instanceof 运算符:

if (animal instanceof Dog) { /* ... */ }

当您只是在 TypeScript 中使用普通对象时,您必须提供一个额外的属性来在运行时区分类型。

type AnimalType = 'dog' | 'cat'

interface Dog extends Animal {
  type: 'dog'
  name: string;
  kind: DogsKind;
}

if (animal.type === 'dog') { /* ... */ }

【讨论】:

  • 不需要额外的属性,你可以在接口中使用鸭子类型。
猜你喜欢
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 2014-07-23
  • 2013-09-21
  • 1970-01-01
  • 2017-08-12
相关资源
最近更新 更多