首页 > 解决方案 > 尝试将布尔和接口传递给组件状态时,React/Typescript 中的属性缺少类型?

问题描述

我是 React 和 Typescript 的新手,我找不到将它们传递到 React.Componet 状态的正确方法。我的代码仍然按预期工作,但我想知道我做错了什么!

class App extends React.Component<{}, { isLoading: boolean, thisCoffeeShop: ICoffeeShop }> {
constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
        isLoading: true                    
    }       
}
//....
}

}

我假设它的打字稿把我扔了

"Property 'thisCoffeeShop' is missing in type '{ isLoading: true; }' but required in type 'Readonly<{ isLoading: boolean; thisCoffeeShop: ICoffeeShop; }>'."

标签: reactjstypescriptreact-native

解决方案


你的状态丢失thisCoffeeShop了,你说会在其中。

this.state = {
  isLoading: true   
  thisCoffeeShop: {...} // no idea what structure ICoffeeShop is              
}

如果您不希望它被要求启动,您可以将该属性设为可选。

React.Component<{}, { isLoading: boolean, thisCoffeeShop?: ICoffeeShop }>


推荐阅读