【问题标题】:class vs interface to describe object类与接口来描述对象
【发布时间】:2019-09-27 18:59:24
【问题描述】:

在 TypeScript 中描述对象的正确方法是什么(可能不仅在 TypeScript 中)。例如,我有一些 get http 请求返回给我一个具有 2 个参数(名称和 id)的对象。 我看到 3 种方式来描述它。 首先是创建接口

export interface MyObject {
  name: string;
  id: number;
}

第二种方式是创建一个类

export class MyObject {
  public name: string;
  public id: number;
}

或同一个类,但有 getter 和 setter

export class MyObject {
  private _name: string;
  private _id: number;

  public get name(): string {
    return this._name;
  }

  public set name(value: string) {
    this._name = value;
  }

  // similarly for id
}

那么什么是最明确和最正确的方法。我主要使用接口来描述一个对象。但是我见过很多项目,其中对象是由类描述的,这三种方法的优缺点是什么。有没有最合适的?

【问题讨论】:

  • 我更喜欢接口,因为它只是描述一个对象,而不是一个为实例化一个对象提供模板的类。
  • 第三版无法编译。私有属性和 setter/getter 应该有不同的名称。以private _name: stringprivate _id: number 为例。

标签: typescript class oop interface


【解决方案1】:

例如,我有一些 get http 请求返回给我一个具有 2 个参数(名称和 ID)的对象。我看到了 3 种方式来描述它。

HTTP 请求获取 JSON 字符串,然后对其进行解析。

动态方式

动态方式是简单地使用 JSON 解析器生成的对象。 interface 是描述它的正确工具:

export interface MyObject {
  name: string;
  id: number;
}

// …
const result = JSON.parse(await fetch(…)) as MyObject;

繁重的OOP方式

这里,JSON 解析器提供与之前相同的对象,但我们更喜欢通过实例化一个类来创建另一个对象:

export class MyObject {
  constructor(public name: string, public id: number) {
  }
}

// …
const { name, id } = JSON.parse(await fetch(…));
const result = new MyObject(name, id);

最大的详细 OOP 方式

与另一个使用 setter 和 getter 的间接方法相同:

export class MyObject {
  private _name: string;
  private _id: number;

  public get name(): string {
    return this._name;
  }

  public set name(value: string) {
    this._name = value;
  }

  public get id(): number {
    return this._id;
  }

  public set id(value: number) {
    this._id = value;
  }
}

// …
const { name, id } = JSON.parse(await fetch(…));
const result = new MyObject();
result.name = name;
result.id = id;

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 2016-03-24
    • 1970-01-01
    • 2014-02-11
    • 2016-08-09
    • 1970-01-01
    • 2021-06-26
    • 2019-04-06
    • 1970-01-01
    相关资源
    最近更新 更多