在 TypeScript 中获取和设置

新手上路,请多包涵

我正在尝试为属性创建 get 和 set 方法:

 private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

设置值的关键字是什么?

原文由 MuriloKunze 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 624
2 个回答

TypeScript 使用类似于 ECMAScript4/ActionScript3 的 getter/setter 语法。

 class foo {
    private _bar: boolean = false;
    get bar(): boolean {
        return this._bar;
    }
    set bar(value: boolean) {
        this._bar = value;
    }
}

这将使用 ECMAScript 5 Object.defineProperty() 功能生成这个 JavaScript。

 var foo = (function () {
    function foo() {
        this._bar = false;
    }
    Object.defineProperty(foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (value) {
            this._bar = value;
        },
        enumerable: true,
        configurable: true
    });
    return foo;
})();

所以要使用它,

 var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

但是,为了完全使用它,您必须确保 TypeScript 编译器以 ECMAScript5 为目标。如果您正在运行命令行编译器,请使用 --target 像这样的标志;

 tsc --target ES5

如果您使用的是 Visual Studio,则必须编辑项目文件以将标志添加到 TypeScriptCompile 构建工具的配置。你可以 在这里 看到:

正如@DanFromGermany 下面建议的那样,如果您只是读取和写入像 foo.bar = true 这样的本地属性,那么拥有一个 setter 和 getter 对就过分了。如果您需要在读取或写入属性时执行某些操作(例如日志记录),您可以随时添加它们。

Getter 可用于实现只读属性。这是一个示例,它还显示了 getter 如何与只读和可选类型交互。

 //
// type with optional readonly property.
// baz?:string is the same as baz:string|undefined
//
type Foo = {
    readonly bar: string;
    readonly baz?: string;
}
const foo:Foo = {bar: "bar"}
console.log(foo.bar) // prints 'bar'
console.log(foo.baz) // prints undefined

//
// interface with optional readonly property
//
interface iFoo {
    readonly bar: string;
    readonly baz?: string;
}

const ifoo:iFoo = {bar: "bar"}
console.log(ifoo.bar)  // prints 'bar'
console.log(ifoo.baz)  // prints undefined

//
// class implements bar as a getter,
// but leaves off baz.
//
class iBarClass implements iFoo {

    get bar() { return "bar" }
}
const iBarInstance = new iBarClass()
console.log(iBarInstance.bar) // prints 'bar'
console.log(iBarInstance.baz) // prints 'undefined'
// accessing baz gives warning that baz does not exist
// on iBarClass but returns undefined
// note that you could define baz as a getter
// and just return undefined to remove the warning.

//
// class implements optional readonly property as a getter
//
class iBazClass extends iBarClass {
    private readonly _baz?: string

    constructor(baz?:string) {
        super()
        this._baz = baz
    }

    get baz() { return this._baz; }
}

const iBazInstance = new iBazClass("baz")
console.log(iBazInstance.bar)  // prints bar
console.log(iBazInstance.baz)  // prints baz

原文由 Ezward 发布,翻译遵循 CC BY-SA 4.0 许可协议

虽然 TypeScript 会分析属性的初始化,但如果您总是想自己处理这种情况,您可以在 — 中设置为 ts.config.json false 对于此设置。

 {
  "compilerOptions": {
    "strict": true,
    "strictPropertyInitialization": false
  }
}

严格的属性初始化 - strictPropertyInitialization 当设置为 true 时,TypeScript 将在声明了类属性但未在构造函数中设置时引发错误。

在这种情况下,您也应该考虑其他情况,您将在下面的链接中看到。

 class UserAccount {
  name: string;
  accountType = "user";

  email: string;//Property 'email' has no initializer and is not definitely assigned in the constructor.
  address: string | undefined;

  constructor(name: string) {
    this.name = name;
    // Note that this.email is not set
  }
}

this.name 具体设置。

this.accountType 默认设置。

this.email 未设置并引发错误。

this.address 被声明为可能未定义,这意味着它不必设置。

如果我们将 strictPropertyInitialization 设置为 false ,编译器不会引发错误

  private _name : string;
  public get name() : string {
    return this._name;
  }
  public set name(v : string) {
    this._name = v;
  }

https://www.typescriptlang.org/docs/handbook/2/classes.html#–strictpropertyinitialization https://www.typescriptlang.org/tsconfig#strictPropertyInitialization

原文由 gurkan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进