簡體   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