新建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,欢迎小伙伴们一起加油学习。
博客讲述在TypeScript中使用set/get存取器时遇到报错,后发现需将编译器设置为输出ECMAScript5或更高,不支持降级到ECMAScript3。还提到只带get不带有set的寄存器自动被推断为readonly,最后作者表示因工作开始学TypeScript。
1534

被折叠的 条评论
为什么被折叠?



