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 构建工具的配置中。可以看到here:
正如@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