设置状态的接口包含枚举值会引发错误

时间:2019-04-11 12:17:58

标签: typescript

尝试运行以下内容:

type Mode = 'signup' | 'signin' | 'forgot-password';

interface IProps {}

interface IState {
  mode: Mode;
}

class SigninSignupModal extends React.Component<IProps, IState> {
  state = {
    mode: 'signup',
  };
}

引发以下错误:

Type 'string' is not assignable to type 'Mode'. ts(2416)

那是为什么?

例如,这很好:

type Mode = 'signup' | 'signin' | 'forgot-password';

let mode: Mode = 'signup';

而且,这很好:

class SigninSignupModal extends React.Component<IProps, IState> {
  construct() {
    this.state = {
      mode: 'signup',
    };
  }
}

1 个答案:

答案 0 :(得分:1)

我想您必须将string强制转换为Mode类型:

this.state = {
  mode: 'signup' as Mode,
};

    this.state = {
      mode: <Mode>'signup',
    };

有关更多信息,请滚动至“类型断言”: https://www.typescriptlang.org/docs/handbook/basic-types.html