我想在接口上创建类,但它看起来是链接,它不尊重只读修饰符。
下面的代码可以正常工作而没有编译器错误:
<img src="/path/to/image.webp" data-mfp-src="/path/to/image.webp" onerror="this.onerror=null;this.src='/path/to/image.jpeg';data-mfp-src='/path/to/image.jpeg'" class="image-popup">
为了使属性“ a”真正变为只读,我也应该在类定义中将其设为只读! 那么接口定义中readonly修饰符的用例是什么?
换句话说,如何通过实现使用正确的修饰符创建接口的接口来确保在创建类时?
答案 0 :(得分:1)
你需要提前定义“D”的类型,注意我把“D”变成了小写的“d”
interface I {
readonly a: string
}
class C implements I{
a= ""
}
let d: I // THIS IS NEEDED
d = new C
d.a = "something" // NOW THIS WON'T WORK
答案 1 :(得分:0)
接口中readonly
关键字的主要思想是在声明接口类型的对象的情况下的约束。
interface ITest {
readonly a: string;
}
const t: ITest = {
a: 'readonly'
}
t.a = 'another value'; // -> Compiler error
在类中实现接口时,该类必须重新声明所推断属性的访问属性
interface ITest {
readonly a: string;
b: string;
c: string;
}
class ATest implements ITest {
a: string = ``;
constructor(public b: string, public c: string) { }
}
const t = new ATest('b', 'c');
t.a = 'another value'; // This is OK
答案 2 :(得分:0)
更令人担忧和惊讶的是,相反的事实也是如此。具有只读属性的对象可以满足该属性不是只读的对象的类型。
我发现了这个问题:https://github.com/microsoft/TypeScript/issues/18770
它是开放的,这可能表明有兴趣以某种方式解决此问题,并且有些人认为这是一个问题。