使用Yarn构建生产版本遇TypeError:'store'属性不存在于类型'{}',如何解决?
解决TypeScript类型错误:Property 'store' does not exist on type '{}'
问题根源
两个报错的核心原因都是Qwerty组件未定义接收的Props类型,TypeScript默认将组件props推断为{}空对象类型,因此无法识别store属性。
解决方案
步骤1:给Qwerty组件添加Props类型定义
修改Qwerty组件代码,导入PuzzleStore并定义组件的Props接口,明确约束store属性的类型:
import { observer } from 'mobx-react-lite' import PuzzleStore from '../stores/PuzzleStore' // 定义组件接收的props类型 interface QwertyProps { store: typeof PuzzleStore } export default observer(function Qwerty({ store }: QwertyProps) { const qwerty = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'] return ( <div> {qwerty.map((row) => ( <div className="flex justify-center"> {row.split('').map((char) => { const bgColor = store.exactGuesses.includes(char) ? 'bg-green-400' : store.inexactGuesses.includes(char) ? 'bg-yellow-400' : store.allGuesses.includes(char) ? 'bg-gray-400' : 'bg-gray-200' return ( <div className={`rounded-m m-px flex h-10 w-10 items-center justify-center uppercase ${bgColor}`} > {char} </div> ) })} </div> ))} </div> ) })
特殊情况处理(若PuzzleStore是Class类)
如果PuzzleStore是Class类而非对象字面量,需要用InstanceType获取类的实例类型:
interface QwertyProps { store: InstanceType<typeof PuzzleStore> }
步骤2:验证类型匹配
确保index.tsx中通过useLocalObservable创建的store类型与Qwerty组件定义的store类型一致。若PuzzleStore是Class类,需改为实例化方式创建:
// 若PuzzleStore是类,需实例化后传入useLocalObservable const store = useLocalObservable(() => new PuzzleStore())
原理说明
TypeScript作为静态类型语言,要求组件的props必须明确类型定义,否则会默认使用最严格的{}类型校验。通过给Qwerty组件添加QwertyProps接口,让TypeScript明确组件接收store属性及其类型,即可消除类型错误。
内容的提问来源于stack exchange,提问作者Laban Bwire
相关产品推荐
相关产品推荐

