TypeScript 中 class 属性的命名约定

Naming convention for class properties in TypeScript

根据 offical style guide 你应该

Avoid prefixing private properties and methods with an underscore.

由于我来自 Java 背景,我通常只使用 this 关键字:

export default class Device {
    private id: string;

    constructor(id: string) {
        this.id = id;
    }

    public get id(): string { // [ts] Duplicate identifier 'id'.
        return this.id;
    }

    public set id(value: string) { // [ts] Duplicate identifier 'id'.
        this.id = value;
    }
}

但是 TypeScript 编译器抱怨:[ts] 重复标识符 'id'.

TypeScript 构造函数中的参数命名是否有约定或最佳实践?

使用 TypeScript 的 getset 属性 会产生错误。

有没有办法在遵循样式指南的同时使用 TypeScript 的 get/set 属性?

回答

如果你想使用 getset 访问器,你必须在私有 属性 前加上下划线。在所有其他情况下不要使用它。我会说将下划线与访问器一起使用是一种特殊情况,尽管它没有明确地写在 Coding guidelines, it doesn't mean it's wrong. They use it in the official documentation.

下划线的原因

首先,我想强调一下fieldproperty之间的区别。在 Java 或 C# 等标准高级 OOP 语言中,字段是私有成员,其他 classes 不应看到它。如果你想在考虑封装的情况下公开它,你应该创建一个 属性.

Java中你这样做(它被称为Bean属性):

private int id;

public int getId() {
    return this.id;
}

public setId(int value) {
    this.id = value;
}

然后你可以通过调用这些方法访问属性:

int i = device.getId();
device.setId(i);

//increment id by 1
device.setId(device.getId() + 1);

另一方面,C# 的设计使其更易于使用属性:

private int id;

public int Id {
    get {
        return this.id;
    }
    set {
        this.id = value;
    }
}

(值始终是分配的值。)

您可以直接为这些属性赋值或获取 属性 值。

int i = device.Id;
device.Id = i;

//increment id by 1
device.Id++;

在普通的Java脚本中,没有真正的字段,因为class成员总是public;我们简单地称它们为属性。

TypeScript 中,您可以定义“真正的”类 C# 属性(带有封装)。你为此使用 Accessors

private _id: number;

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

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

用法:

let i: number = device.id;
device.id = i;

//increment id by 1
device.id++;

必须在这里使用下划线,原因有二:

  1. 在Java脚本中,所有class 成员都是public。因此,通过在 private 属性 之前加上下划线,我们表示此 属性(字段)是私有的,并且应该仅由其 public 属性 访问。
  2. 如果您将 private 和 public 属性 命名为相同的名称,Java脚本解释器将不知道是访问 private 还是 public 属性。因此你得到了你正在写的错误:[ts]重复标识符'id'.

如果问题是严格的:

Is there a way to follow the [typeScript] style guide and also use the get/set properties of TypeScript?

TypeScript 风格指南说的是:

Avoid prefixing private properties and methods with an underscore.

然后您可以使用 $(美元符号)代替 _(下划线)作为私有字段的前缀。通过这种方式,你们都摆脱了 [ts] Duplicate identifier 'blablabla' 错误,同时仍然遵守 TypeScript 样式指南。

此外,但这只是我的意见,.$组合比._组合更具可读性。

对于属性访问器,您使用 _

请参阅来自 Microsoft https://www.typescriptlang.org/docs/handbook/classes.html#accessors 的示例:

const fullNameMaxLength = 10;

class Employee {
  private _fullName: string;

  get fullName(): string {
    return this._fullName;
  }

  set fullName(newName: string) {
    if (newName && newName.length > fullNameMaxLength) {
      throw new Error("fullName has a max length of " + fullNameMaxLength);
    }

    this._fullName = newName;
  }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
  console.log(employee.fullName);
}