繁体   English   中英

Typescript react类:将State类型添加为接口或null

[英]Typescript react class: add State type as interface or null

在react中,当我们使用打字稿时,典型的状态类型声明如下

import * as React from "react"

interface IState {
  someState: string
}

class MyClass extends React.Component<{}, IState> {
  state = {
    someState: "test"
  }

  // etc...
}

我现在的问题是我也希望state = null有效,即我知道我可以通过someState?来使someState可选someState? ,但是如何在使状态为可空状态的同时仍在类上使用IState接口?

整个状态为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM