Properties 不带setter的属性的TypeScript接口签名。
比如说,我们班上有一个典型的能手Properties 不带setter的属性的TypeScript接口签名。,properties,interface,typescript,setter,getter,Properties,Interface,Typescript,Setter,Getter,比如说,我们班上有一个典型的能手 class Employee implements IEmployee { private _fullName: string; get fullName(): string { return this._fullName; } } 以及一个与之配合使用的界面 interface IEmployee{ fullName: string; } 当通过此接口处理实例时,如果我们尝试分配给fullName,编译
class Employee implements IEmployee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
}
以及一个与之配合使用的界面
interface IEmployee{
fullName: string;
}
当通过此接口处理实例时,如果我们尝试分配给fullName,编译器不会警告我们缺少setter,JS运行时只接受任何分配,不会抛出错误。有没有办法将接口成员标记为只有getter或setter
我见过,但它已经很旧了,我想知道是否有改进。这是一个有趣的问题。在TypeScript中,只读属性的概念与其他语言有细微的不同 在许多语言中,如果试图设置带有getter(但没有setter)的属性,但TypeScript没有设置,则该属性将引发编译器错误 该属性仍然是只读的,因为如果您尝试设置它,它不会有任何区别;该集合将以静默方式失败 下面是一个没有任何接口的示例:
class Example {
get name() {
return 'Steve';
}
}
var y = new Example();
y.name = 'Example 2';
alert(y.name);
当我使用x.name='example2'时,没有编译器警告代码>
如果有编译器警告,我希望随后会有一种方法指定接口中属性的只读性。但是,正如您所期望的,鉴于上述信息,您不能在接口上设置只读属性
interface Test {
name: string;
}
class Example {
get name() {
return 'Steve';
}
}
var x: Test = new Example();
x.name = 'Example 1';
alert(x.name);
var y = new Example();
x.name = 'Example 2';
alert(x.name);
这意味着您只能通过使用一个方法来获取属性的值(显然没有允许设置属性的方法)来实现只读性
typescript中的属性现在可以具有“readonly”修饰符,从而实现所需的result
接口i员工{
只读全名:字符串;
}
在没有setter的情况下,JS行为几乎已经强制执行了ReadOnlynes。问题在于它的沉默本质——悄悄地吞噬价值。理想的解决方案(希望即将出现)是允许TS接口成员被标记为只有getter\setter。另一种选择是,transpiler在没有getter setter的情况下生成空getter setter,这只会抛出一个错误(至少对于setter来说,这是我们整个团队所期望的行为)。最后一个乏味的解决方案是,如果不需要实际的setter,那么总是手工创建一个抛出setter。在没有setter的情况下,JS行为已经在很大程度上强制实现了readonlines。
是-虽然是“强制”,但我说的更多的是编译器警告、扭曲的红线和某种声音警报。示例代码显示集合尝试的静默放弃。同时,使用属性访问方法是获得编译时保证不会尝试设置的唯一方法。在GitHub上发布的关于此问题的问题对于此问题缺乏活动感到非常惊讶。只读属性非常有用,是我尝试在TypeScript中实现的第一个模式之一。
interface Test {
getName: () => string;
}
class Example {
getName() {
return 'Steve';
}
}
var x: Test = new Example();
//x.getName('Obviously not');
//x.getName() = 'Obviously not';
alert(x.getName());
var y = new Example();
//y.getName('Obviously not');
//y.getName() = 'Obviously not';
alert(y.getName());