TypeScript 类 的私有构造函数变量和 public 吸气剂

Private constructor variables and public getters for TypeScript classes

我来自 C# 背景。我的大部分 类 都设计为不可变的。我想知道在 TypeScript 类.

中使用私有构造函数变量和 public getter 访问数据是否是一种好习惯

例如:

class UnitType {
   constructor(private code: string, private name: string, private unitType: string) {

}

get Code(): string {
    return this.code;
}
get Name(): string {
    return this.name;
}
get UnitType(): string
    return this.unitType;
}

我似乎找不到任何像上面这样的 TypeScript 代码示例。我错过了什么吗?

是的,这是一个很好的做法。封装总是一件好事:它减少了 "mistake surface" 并降低了程序员的认知负担(更少的东西 - public,可见 - 担心)。

虽然您可以使用 ES5 模拟私有属性,但这并不是 natural/trivial 或非常可读的方式(某些替代方案甚至会导致性能损失)。所以你不会看到太多这样的代码,因为 JavaScript 本身没有私有修饰符。

此外,在 typescript 中标记为私有的属性仅在编译时是私有的。由于它们的运行时是 JavaScript,如前所述,它不知道什么是私有的,因此它们将是可访问的。

您可以使用 public readonly 关键字将您的 class 简化为:

class UnitType {
    constructor(
        public readonly code: string, 
        public readonly name: string, 
        public readonly unitType: string) {
    }
}

// Usage:
var type1 = new UnitType("a", "b", "c");

// error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
type1.code = "aa";