我正在尝试为属性创建get和set方法:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
Run Code Online (Sandbox Code Playgroud)
设置值的关键字是什么?
目前,TypeScript不允许在接口中使用get/set方法(访问器).例如:
interface I {
get name():string;
}
class C implements I {
get name():string {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,TypeScript不允许在类方法中使用Array Function Expression:例如:
class C {
private _name:string;
get name():string => this._name;
}
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以在接口定义上使用getter和setter?
我们在其中一个课程中有一个典型的getter,比方说
class Employee implements IEmployee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
}
Run Code Online (Sandbox Code Playgroud)
以及使用它的界面
interface IEmployee{
fullName: string;
}
Run Code Online (Sandbox Code Playgroud)
当通过此接口使用实例时,如果我们尝试分配给fullName,编译器将不会警告我们没有setter,并且JS运行时只是吞下任何赋值并且不会抛出错误.有没有办法将接口成员标记为只有getter或者只有setter?
我看过这篇文章,但它已经很老了,我想知道,如果有什么改进的话.