简体   繁体   English

无法分配给“ initialState”,因为它是只读属性

[英]Cannot assign to 'initialState' because it is a read-only property

Can't assign to a read-only property in constructor when it run in method, 在方法中运行时,无法将其分配给构造函数中的只读属性,

the typescript version is 3.4.1 打字稿版本是3.4.1

class Example {
   readonly initialState: any
   constructor(){
      this.someMethod()
   }
   private someMethod(){
     this.initialState = 'someState'
   }

}

readonly properties can only be initialized in place during declaration, or inside the constructor . readonly属性只能在声明过程中或在构造函数中初始化 The rationale here is that that method could potentially be called from somewhere else in your code, and attempt to set the property value again, so TypeScript blocks it entirely. 这里的理由是,该方法可能会在代码中的其他位置调用,并尝试再次设置属性值,因此TypeScript会完全阻止它。

PS. PS。 I believe the code was just not copy-and-pasted correctly, since there's no setState() method in your class; 我相信代码只是没有正确地复制粘贴,因为您的类中没有setState()方法。 your code would not run. 您的代码将无法运行。 I'm assuming you meant to say something like this.initialState = 'someState' . 我假设您要说类似this.initialState = 'someState' If you want to revise your question, there might be a different answer. 如果您想修改问题,可能会有不同的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法分配给“状态”,因为它是常量或只读属性 - Cannot assign to 'state' because it is a constant or a read-only property 无法分配给“布尔”,因为它是常量或只读属性 - Cannot assign to 'Boolean' because it is a constant or a read-only property 角度2 | 无法分配给数组,因为它是常量或只读属性 - Angular 2 | cannot assign to array because it is a constant or a read-only property 无法分配给“total”,因为它是一个常量或只读属性 - Cannot assign to 'total' because it is a constant or a read-only property 角度无法分配给“名称”,因为它是常量或只读属性 - Angular Cannot assign to 'name' because it is a constant or a read-only property TS 2540:无法分配给样式,因为它是只读属性 - TS 2540: Cannot assign to style because it is a read-only property Nuxt TypeScript:无法分配给“名称”,因为它是只读属性 - Nuxt TypeScript: Cannot assign to 'name' because it is a read-only property 即使属性未标记为只读,打字稿“无法分配给属性,因为它是常量或只读” - Typescript “Cannot assign to property, because it is a constant or read-only” even though property is not marked readonly “无法分配给 var,因为它是只读属性。” 使用 Jasmine 测试框架进行角度测试 - "Cannot assign to var because it is a read-only property." in angular test using Jasmine Test Framework 错误 TS2540:无法分配给“i”,因为它是常量或只读属性 - error TS2540: Cannot assign to 'i' because it is a constant or a read-only property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM