[英]Typescript react class: add State type as interface or null
In react, when we use typescript a typical state type is declared as follows 在react中,当我们使用打字稿时,典型的状态类型声明如下
import * as React from "react"
interface IState {
someState: string
}
class MyClass extends React.Component<{}, IState> {
state = {
someState: "test"
}
// etc...
}
My issue now is that I also want state = null
to be valid ie I know that I can make someState
optional via someState?
我现在的问题是我也希望state = null
有效,即我知道我可以通过someState?
来使someState
可选someState?
, but how can I still use IState
interface on my class while making state nullable? ,但是如何在使状态为可空状态的同时仍在类上使用IState
接口?
It's not very reacty to have the entire state be null
, but I don't see why this wouldn't work: 整个状态为null
并不是很反感,但我不明白为什么这不起作用:
import * as React from "react";
interface IState {
someState: string;
}
type INullableState = IState | null;
class MyClass extends React.Component<{}, INullableState> {
state = {
someState: "test",
};
// etc...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.