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

时间:2018-09-11 14:19:19

标签: reactjs typescript

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

System.IO.FileNotFoundException: Could not load file or assembly 'System.ServiceProcess.ServiceController, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

我现在的问题是我也希望import * as React from "react" interface IState { someState: string } class MyClass extends React.Component<{}, IState> { state = { someState: "test" } // etc... } 是有效的,即我知道我可以通过state = null使someState为可选,但是我怎么仍可以使用someState?使状态可为空时在我的类上显示接口?

1 个答案:

答案 0 :(得分:1)

entire 状态设为null并不是很反感,但我不明白为什么这不起作用:

import * as React from "react";

interface IState {
  someState: string;
}

type INullableState = IState | null;

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

  // etc...
}