【问题标题】:How to declare a state variable as a Type on Typescript如何在 Typescript 上将状态变量声明为类型
【发布时间】:2021-07-20 17:41:39
【问题描述】:

我有这种类型:

export type AVAILABLE_API_STATUS =
  | "Created"
  | "Process"
  | "Analisis"
  | "Refused";

我想知道如何使用上述类型创建状态。

我尝试过:

const [state] = React.useState<AVAILABLE_API_STATUS>("Refused");

但它要求我在 Type 之前使用 typeof:

const [status] = React.useState<typeof AVAILABLE_API_STATUS>("Refused");

但它不接受'Refused'值;

【问题讨论】:

  • AVAILABLE_API_STATUS 是如何准确定义的?你说的是export type,但显然不是这样。
  • 错误消息表明它是一个,而您声称您将它声明为一个类型。
  • 您在"Created" 之前有一个| 字符。尝试删除它。
  • @Isuru 没关系
  • @zerkms 谢谢我今天学到了一些东西。 :)

标签: javascript reactjs typescript types typeof


【解决方案1】:

在错误消息中显示 AVAILABLE_API_STATUS 而不是您在上面定义的 AVAILABLE_API。有没有可能你有 const AVAILABLE_API_STATUStype AVAILABLE_API 并且你在代码中混淆了它们? 因为这对我有用:

export type AVAILABLE_API =
  | 'Created'
  | 'Process'
  | 'Analisis'
  | 'Refused';

export const TestComponent: React.FC = () => {
  const [state, setState] = React.useState<AVAILABLE_API>('Refused');
  return (
    <button
      type="button"
      onClick={() => setState('Refused')}
    >
      {state}
    </button>
  );
};

【讨论】:

  • 你好,奥普西。首先,谢谢。我已经编辑了上面的标签
猜你喜欢
  • 2016-12-23
  • 2015-07-25
  • 1970-01-01
  • 2015-12-31
  • 2021-07-27
  • 2010-12-22
  • 1970-01-01
  • 2013-06-17
  • 2018-08-23
相关资源
最近更新 更多