新建Employee.ts文件,代码如下:
let passcode = "以马内利";
class Employee{
private _fullName:string;
get fullName():string{
return this._fullName;
}
set fullName(newName:string){
if(passcode&&passcode=="以马内利"){
this._fullName=newName;
}else{
console.log("错误:口令不对");
}
}
}
let employee = new Employee();
employee.fullName="张三";
if(employee.fullName){
alert("员工名字为:"+employee.fullName);
}
执行命令行:
tsc Employee.ts
发现报错
- error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
后来发现只要在命令行中指定为ECMAScript5更高就可以了。具体如下
tsc Employee.ts -t es5
总结:在TypeScript中使用set/get存取器,需要将编译器设置为输出ECMAScript5或更高。不支持降级到ECMAScript3。
tips:只带get不带有set的寄存器自动被推断为readonly。
最近因工作需要,我开始从零开始学习TypeScript,欢迎小伙伴们一起加油学习。