【问题标题】:typescript initialize object with read-only property in-hand打字稿使用只读属性初始化对象
【发布时间】:2019-06-11 18:16:11
【问题描述】:

有没有办法初始化一个对象字面量并同时声明它的接口与只读属性?

例如

let a = { readonly b: 2, readonly c: 3 }

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用as const 断言:

    let a = { b: 2, c: 3 } as const // typed as { readonly b: 2; readonly c: 3; }
    a.b = 2 //Cannot assign to 'b' because it is a read-only property.
    

    如果您只希望某些道具是只读的,那实际上是不可能的,最好的办法是使用Object.assign,其中一部分包含只读属性,另一部分包含可变属性:

    let a = Object.assign({ b: 2, c: 3 } as const, {
      d: 0
    });
    a.b = 2 // err
    a.d = 1 //ok
    

    【讨论】:

    • 但您仍然可以更改 b 和 c 属性
    • 不,你不能。 “无法分配给 'b',因为它是只读属性。”
    • @JurajKocan 不是将属性设为只读的重点吗?
    • @ritaj 你用的是什么 ts 版本?我仍然可以写这个 a.b = 3 在 ts 3.5.1 中没有错误
    • 确实有效!我写 a.b = 3 时出错。使用 typescript 3.4.5
    【解决方案2】:

    你可以用自定义类型来写

    type Point = {
      readonly x: number;
      readonly y: number;
    };
    const a: Point = {
      x: 1,
      y: 2,
    };
    
    a.x = 2; // ERROR Cannot assign to 'x' because it is a constant or a read-only property.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2021-07-24
      • 2018-08-14
      相关资源
      最近更新 更多