尝试运行以下内容:
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',
};
}
}
答案 0 :(得分:1)
我想您必须将string
强制转换为Mode
类型:
this.state = {
mode: 'signup' as Mode,
};
或
this.state = {
mode: <Mode>'signup',
};
有关更多信息,请滚动至“类型断言”: https://www.typescriptlang.org/docs/handbook/basic-types.html