欢迎加入社区!
您的英语很完美,别担心,继续努力,并始终尽可能多地发布数据,以便我们为您提供帮助。
你的错误很清楚,但你的问题是理解 Typescript 的混乱信息,让我们分解一下。
Property 'store' does not exist on type 'Readonly<AppInitialProps & { Component: NextComponentType<NextPageContext<any, AnyAction>, any, {}>; router: Router; __N_SSG?: boolean | undefined; __N_SSP?: boolean | undefined
; }> & Readonly<...>'.
您需要担心要从此行中提取的属性store:
const { Component, store } = this.props;
错误消息是属性store 在this.props 中不存在。 TypeScript 将检查属性是否存在,他通过检查类型来做到这一点。 this.props 具有以下类型(来自错误消息):
Readonly<AppInitialProps & { Component: NextComponentType<NextPageContext<any, AnyAction>, any, {}>; router: Router; __N_SSG?: boolean | undefined; __N_SSP?: boolean | undefined
; }> & Readonly<...>
我建议您查看TypeScript advanced types 以了解Readonly 是什么以及您在使用TS 时会看到的其他内容。但是,简而言之,上面的类型是多种类型的组合,试着读成这样:
Readonly<A & B & C>
& 运算符结合了两种类型。上面的结果类型将是 A、B 和 C 类型的组合,属性将为 readonly,这意味着您不应更改属性的值。
这是我为您制作的示例:
type PersonProfile = {
name: string;
};
type PersonAge = {
age: number
}
type FullProfile = PersonProfile & PersonAge;
const personA: PersonProfile = { name: "Murillo" };
personA.name = "Henrique"; // ok
const fullPersonData: PersonProfile & PersonAge = { name: "Murillo", age: 103 };
const anotherFullPersonData: FullProfile = { name: "Henrique", age: 574 }; // The same
const personB: Readonly<PersonProfile> = { name: "John" };
personB.name = "Doe"; // Error, Cannot assign to 'name' because it is a read-only property
解决方案
您可以执行以下操作来消除错误并测试一切是否正常。
const { Component, store } = this.props as any;
这会将this.props 的类型从那些杂乱无章的东西更改为any,并且any 可以包含任何属性。您可以出于测试目的这样做,但我不建议使用它,事实上,eslint 之类的工具可能不允许您这样做(有点破坏了使用 TypeScript 的目的)。
您还会注意到您将丢失编辑器的建议,因为他不再知道store 和Component 是什么。
我建议您从您的组件中更改props 的类型,因此该类型将是它当前具有的类型+您要提取的商店。你可能会在这方面做一些工作,但我保证这会是很好的学习。
This 可能会帮助您更改整个组件中的道具类型(没有全部阅读)。
解决方案 2
// ...
type MyAmazingReduxStore = { store: any } // Change *any* to the correct type. check the redux documentation
// ...
const { Component, store } = this.props as Readonly<typeof this.props & MyAmazingReduxStore>
这会将props 的类型更改为原来的类型+您的新类型。问题是你不会改变整个组件中道具的类型,只是在那一行代码。
如果现在信息太多,请不要担心,继续努力!