English 中文(简体)
2. 如何在构成部分内以文字说明的形式确定只读的财产 吗?
原标题:How to set a readonly property with typescript in componentDidMount?

I would like to have constant (readonly) properties in a React.Component class. The problem is that I should not initialize them in the constructor since they trigger side effects like setInterval or fetch. Instead I should initialize them in componentDidMount but since I use strict type checkings I must also indicate their types can be undefined (or null, whatsoever). That s what I want to avoid because then I am forced to check if the value is not null every time I use it despite I know it already, and I also wanna avoid using the "!" operator as much as possible because then I don t have type errors when I forget to initialize them.

Does there exist a clean solution? Some way to tell typescript that componentDidMount is like a constructor and so a property can be initialized only there?

问题回答

没有,也没有这样做的干净方法。 字典对班级的理解有其内在的特性,即班级大约有两个领域:(与问题无关):

  • The constructor: where fields -and their backing types- are being initialized
  • The rest of the class: where fields are being used - and their backing types don t change

退一步:知道<代码>componentDidMount<>/code>是一种初始化功能,类似于编码中的“隐蔽假设”。 这就是说,它不是贾瓦古典的一部分,法典本身也没有解释这一点。 你们在从事重修班时会知道什么。 缺乏良好工具的类型系统是因为很难在类型系统地描述每个框架的细微差别。

由于许多开发商迁到,因此,这些隐蔽的假设已经破灭。 它们不需要随着时间的推移而改变财产类型——它更多地围绕变量和范围,而后者更适合类型系统。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签