简体   繁体   English

TypeScript 为什么使用传统类而不是接口?

[英]TypeScript why use traditional classes instead of interfaces?

I can do this:我可以做这个:

enum DogsKinds {
  Labrador,
  Aski
}

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

And then init a dog object:然后初始化一个狗对象:

const dog = new Dog();

However I can do the same with interface:但是我可以对界面做同样的事情:

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

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

And get the same result - easier.并获得相同的结果 - 更容易。

What are the differences, when to use interface and when to use classes, is there a best practice or rule of thumb?何时使用接口和何时使用类有什么区别,是否有最佳实践或经验法则?

It seems that interfaces are easier to work with, if I wrong please correct me.似乎接口更容易使用,如果我错了请纠正我。

I think one important difference is finding out at runtime which kind of object you are dealing with when using inheritance .我认为一个重要的区别是在运行时找出您在使用继承时正在处理的对象类型

With classes you can use the instanceof operator:对于类,您可以使用instanceof运算符:

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

When you are just using plain objects with TypeScript you will have to supply an additional property to differentiate the types during runtime.当您仅在 TypeScript 中使用普通对象时,您将必须提供一个额外的属性来在运行时区分类型。

type AnimalType = 'dog' | 'cat'

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM