Typescript 类实现接口不尊重 readonly 修饰符

Sae*_*tad 5 interface class readonly typescript

我想基于接口创建类,但它看起来链接它不尊重 readonly 修饰符。

下面的代码在没有编译器错误的情况下工作:

interface I {
  readonly a: string
}

class C implements I{
  a= ""
}
const D = new C
D.a = "something"
Run Code Online (Sandbox Code Playgroud)

为了使属性“a”真正只读,我也应该在类定义中将其设为只读!那么接口定义中 readonly 修饰符的用例是什么?

换句话说,我如何通过实现使用正确修饰符创建它的接口来确保何时创建一个类?

VRo*_*oxa 0

接口中关键字的主要思想readonly是声明接口类型的对象时的约束。

interface ITest {
    readonly a: string;
}

const t: ITest = {
    a: 'readonly'
}

t.a = 'another value'; // -> Compiler error
Run Code Online (Sandbox Code Playgroud)

在类中实现接口时,类必须重新声明推断的属性的访问属性

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
Run Code Online (Sandbox Code Playgroud)