【问题标题】:Type '{}' is missing the following properties from type 'Message':类型“{}”缺少“消息”类型的以下属性:
【发布时间】:2019-10-10 21:49:38
【问题描述】:

使用对象扩展运算符时出现以下错误:

Type '{}' is missing the following properties from type 'Message':...

returnMessage 被分配了一个类型,所以我不知道我应该做什么?

我的代码:

  dispatchMessages = (message: Message): void => {
    this.setState({ messageFromDashboard: message });
    const messageCopyFromState: Message = { ...this.state.messageFromDashboard };
    let returnMessage: Message;
    setTimeout(() => {
      returnMessage = this.createMessageFromServer(messageCopyFromState);
      this.setState({ messageToDashboard: returnMessage });
    }, 1000);
  }

提前致谢

【问题讨论】:

  • 您最初是如何在构造函数中分配messageFromDashboard 的状态的?

标签: reactjs typescript


【解决方案1】:

您的组件状态的类型是什么?您可以尝试这样定义:

type State = {
  messageFromDashboard: Message
  // your other state properties
}

type Props = any;

class MyComponent extends React.Component<Props, State> {

}

【讨论】:

    【解决方案2】:

    在 react-native 中,如果你想使用 state 的属性和它的类型,那么首先你必须用它的每个属性声明 state,你将使用下面的检查示例:

    interface IState {
      message: Message;
    }
    
    export class MyComponent extends React.PureComponent<IProps, IState> {
      
      constructor(props : any) {
        super(props);
        this.state = {
          message: new Message()
        };
      }
      
      render() {
        return <span>{`${this.props.superhero} health is: ${this.state.health}`}</span>
      }
    }

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 2020-10-28
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多