Typescript中接口和类之间的区别

Emr*_*ürk 34 interface class models typescript angular

在Typescript接口和类之间有什么不同?我什么时候使用Class?我什么时候使用Interfaces?他们有什么好处?

我需要为我的后端服务器(使用Angular 2执行它)创建某种类型的http请求,例如:},

"fields": {
  "project": {
      "id": "10000"
  },
  "summary": "something's wrong",
  "issuetype": {
      "id": "10000"
  },
  "assignee": {             // not neccesary required
      "name": "homer"
  },
  "reporter": {
      "name": "smithers"
  },
  "priority": {            // not neccesary required
      "id": "20000"
  }
}
Run Code Online (Sandbox Code Playgroud)

我应该用什么来构建这些模型?谢谢!

Jer*_*emy 35

2019:差异和用法更新

首先,有明显的区别:语法。这是一个简单但需要理解的区别:接口属性可以以逗号或分号结尾,而类属性只能以分号结尾。现在有趣的东西。关于何时使用和不使用的部分可能是主观的-这些是我为团队成员提供的准则,但是出于有效的原因,其他团队也可能会有其他准则。如果您的团队有其他不同的想法,请随时发表评论,我很想知道为什么。

接口:允许定义一种类型,该类型将在设计和编译期间用于强类型化。它们可以“实现”或“扩展”,但不能实例化(您不能new)。在向下编译为JS时它们会被删除,因此它们不占用空间,但是在运行时也无法进行类型检查,因此您无法检查变量是否在运行时实现了特定类型(例如foo instanceof bar),除非通过检查其属性来实现。具有:使用Typescript进行接口类型检查

何时使用接口:当需要为对象创建属性和函数的协定时,可以使用它们,这些约定将在代码中的多个地方使用,尤其是在多个文件或函数中。此外,当您希望其他对象开始的这组基本特性,如具有的使用Vehicle接口,多个类实现具体类型的车辆,如CarTruckBoat(例如class Car implements Vehicle)。

何时不使用接口:当您想要具有默认值,实现,构造函数或函数(而不仅仅是签名)时。

:还允许定义一个类型,该类型将在设计和编译期间用于强类型化,另外,还可以在运行时使用。这也意味着代码没有被编译出来,因此会占用空间。这是@Sakuto提到的一个关键区别,但它所带来的影响不仅仅是空间。这意味着可以对类进行类型检查,即使在已转译的JS代码中也可以保留对“它们是谁”的理解。进一步的区别包括:类可以使用实例化new,可以扩展,但不能实现。类可以具有构造函数和实际功能代码以及默认值。

何时使用类:当您要创建其中包含实际功能代码的对象时,请使用构造函数进行初始化,和/或使用来创建它们的实例new。同样,对于简单的数据对象,您可以使用类来设置默认值。另一个您想使用它们的时间是在进行类型检查时,尽管有一些接口的解决方法(如果需要)(请参阅接口部分的OS链接)。

什么时候不使用类:当您有一个简单的数据接口时,不需要实例化它;当您希望由其他对象实现它时;当您只是想将一个接口放置在现有对象上时(请考虑类型定义文件)或当它占用的空间过大或不必要时。附带说明一下,如果您查看.d.ts文件,您会发现它们仅使用接口和类型,因此在转换为TS时将其完全删除。

最后要注意的是,除了类和接口之外,还有其他两个选项,第一个是称为“类型”的东西,它与接口非常相似,但请查看此SO帖子,特别是2019 Update答案:Typescript:Interfaces vs Types。最后一个选择是使用TS进行函数式编程(不是OOP)。

有关示例的完整故事,请访问PassionForDev.com,有关示例与继承的更多关于类与继承的良好阅读,请访问https://jameshenry.blog/typescript-classes-vs-interfaces/

  • 我刚刚发现类的 instanceof 有一些有趣的东西,您必须创建一个类的新实例,以便它能够检查类型,而不仅仅是将其用作类型。仔细想想,这似乎很明显,但是当我尝试编写示例时犯了错误。因此,`const classExample1: ClassExample = { status: 200 }` 不适用于 instanceof 但 `const classExample2 = new ClassExample()` 会。 (2认同)

Sak*_*uto 21

角2风格指南则建议使用ClassInterface的打字.主要区别在于class编译时会持续存在,而Interface纯粹被删除,因为它们不能用于任何用途.

只需在整个项目中保持一致,并且更喜欢使用styleguide方法class,也就是说,有一天您可能需要添加method到您的项目中models.

  • angular 风格指南没有指定使用 `class` 而不是 `interface` 的原因。它说要“考虑”您的要求。在这里阅读更多:https://github.com/angular/angular/issues/19632 (3认同)
  • “谁知道呢,也许有一天你需要为你的模型添加方法。” 接口也支持方法。 (2认同)

Jos*_*ose 7

Simply Class是用来创建对象的,而Interface可以帮助您这些对象应包含的内容。

类就像一个蓝图/模板,我们可以使用它来创建对象。接口就像合同,类必须就实现该接口或定义该蓝图应包含的内容达成一致。

一个简单的类:

class Car {
    engine: string; // 'var' is not used;

    constructor(engine: string) { // This is how we create constructor
        this.engine = engine;
    }

    display(): void { // 'function' keyword is not used here.
        console.log(`Engine is ${this.engine}`); // just a log.
    }
}

var objCar = new Car('V8'); // creates new onject
objCar.display(); // output: Engine is V8
console.log(objCar.engine); // output: V8 (accessing member here)
Run Code Online (Sandbox Code Playgroud)

一个简单的界面:

    interface IPerson { // This is how we create an interface.
        firstName: string, // use commas to separate.
        lastName: string, // In classes we use semi-colon to separate.
        displayDetails: (number) => string
    }

    // We are going to store 'interface object' in a variable.
    // i.e. we are implementing interface with variable(not class!!)
    var customer: IPerson = {

        firstName: 'jose jithin', // 'implements' variables
        lastName: 'stanly',

        // Now method implementation.
        // Note: the syntax of 'displayDetails' maybe a bit confusing (given below)
        // as two colons are used.
        // It specifies a return type(string) here for this method. 
        displayDetails: (rank): string => { return `This person has rank ${rank}. ` }  

        // It can be rewritten as following too.
        displayDetails: (rank) => { return `This person has rank ${rank}. ` };
        // i.e. return type need not be specified, just like a normal method definition syntax.
    }

    console.log(customer.firstName); // output: jose jithin

    console.log(customer.lastName);  // output: stanly

    console.log(customer.displayDetails(1)); // output: This person has rank 
Run Code Online (Sandbox Code Playgroud)

我的文章详细介绍了类和接口。这可能有助于您理解。


Wil*_*een 5

接口

  • 描述一个物体应该是什么样子
  • 仅存在于编译时,唯一目的是进行类型检查

课程

  • 用作实例化/生成对象的蓝图
  • 可以实现一个接口,这意味着它必须至少实现该接口的所有属性/方法

例子:

interface Person {
    name: string;
    id: number;
    doStuff: () => void;
}

// implements Person says: You have to at least implement these things
// which are located on the person interface 
class employee implements Person {
    constructor(public name: string, public id: number){}

    doStuff () {console.log('Doing stuff')}
}

// interfaces can also describe variables and parameters
const p1: Person = {
    name: 'foo',
    id: 34,
    doStuff () {console.log('Doing stuff')}
}
Run Code Online (Sandbox Code Playgroud)