简体   繁体   English

类型“只读<{}>”上不存在属性“产品”

[英]Property 'products' does not exist on type 'Readonly<{}>'

EDIT on @Lesiak request:编辑@Lesiak 请求:

Here is my getProducts call这是我的 getProducts 电话

// @api/shopifyProducts.ts

import Client from 'shopify-buy'

const client = Client.buildClient({
  // TODO: add to dotenv
  domain: 'some-domain.myshopify.com',
  storefrontAccessToken: 'example-token-2597293846729587293875'
})

export const getProducts = async () => {
  try {
    const data = await client.product.fetchAll()
    const products = await data.map((item) => {
      return {
        title: item.title,
        description: item.description
        // images: item.images
      }
    })

    return products
  } catch (error) {
    throw new Error(`Product API fetch failed: ${error}`)
  }
}

I have also refactored my component like this:我还像这样重构了我的组件:

import React, { Component } from 'react'
import { getProducts } from '@api/shopifyProducts'

class TheListProducts extends Component<{}> {
  constructor(props) {
    super(props)

    this.state = {
      products: null
    }
  }
  async componentDidMount() {
    this.setState({
      products: await getProducts()
    })
    console.log(this.state.products) ==> Error: Property 'products' does not exist on type 'Readonly<{}>'
  }

  render() {
    return <p>Hey</p>
  }
}

export default TheListProducts

Initial question:最初的问题:

Morning fellow developers,各位开发者早安,

I stumbled upon an issue I can't solve on my own even by doing an extensive research on the web.我偶然发现了一个即使对 web 进行广泛研究也无法自行解决的问题。 Since I am new to TS, I can see I don't understand in 100% what is really happening.由于我是 TS 的新手,我可以看到我 100% 不明白到底发生了什么。

I have a component in React, where I async fetch content from Shopify content and I want to print it inside render function.我在 React 中有一个组件,我从 Shopify 内容中异步获取内容,我想在渲染 function 中打印它。

import React, { Component } from 'react'
import { getProducts } from '@api/shopifyProducts'

interface Product {
  title: any
  description: any
}

interface ListState {
  products: {
    [key: string]: Product | Function
  }
}

class TheListProducts extends Component<{}, ListState> {
  async componentDidMount() {
    this.setState({
      products: await getProducts()
    })
  }

  render() {
    return <p>{this.state.products}</p>
  }
}

export default TheListProducts

I receive the following error:我收到以下错误:

(property) products: {
    title: string;
    description: string;
}[]
Type '{ title: string; description: string; }[]' is not assignable to type '{ [key: string]: Product; }'.
  Index signature is missing in type '{ title: string; description: string; }[]'.ts(2322)

Here is how it looks in the browser:这是它在浏览器中的外观: 浏览器

I can read, and I think I understand the error, but have no clue whatsoever what to do about it.我可以阅读,我想我理解这个错误,但不知道该怎么做。

If anyone could explain it to me in plain english it would be awesome.如果有人能用简单的英语向我解释,那就太棒了。

Based on the web research I tried enhancing the Product interface like this:基于 web 研究,我尝试像这样增强产品界面:

interface Product {
  title: string
  description: string
  [key: string]: string | number | undefined | Function
}

but it's like going in blind...但这就像盲人一样...

If you are using class component you should define the type of the state and props:如果您使用 class 组件,您应该定义 state 和道具的类型:

class App extends React.Component<MyProps, MyState> {

You can look here for more details您可以在这里查看更多详细信息

如何正确扩展 DocumentInitialProps,同时显示错误“只读类型上不存在属性<renderpageresult reactelement"< div><div id="text_translate"><p> 我是 Typescript 的初学者。 我正在研究 Nextjs Typescript 项目。 基本上,我想要做的是通过body标签将userCurrency值从服务器端传递给客户端。 我正在处理_document.tsx文件。 问题是我收到了这个错误</p><p><a href="https://i.stack.imgur.com/sX2Np.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sX2Np.png" alt="在此处输入图像描述"></a></p><p> 我从错误消息中收集到的是DocumentInitialProps上不存在userCurrency ,并且参考其他 stackoverflow 帖子我正在尝试将附加属性userCurrency扩展/添加到DocumentInitialProps 。 我在这里试过了,忽略黄色条..</p><p> <a href="https://i.stack.imgur.com/9O5kl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9O5kl.png" alt="在此处输入图像描述"></a></p><p> 如您所见,我创建了NewDocumentInitialProps 。 但是,错误仍然存在。 我究竟做错了什么? 如何向DocumentInitialProps添加自定义属性?</p><pre> import { Fragment } from "react"; import Document, { DocumentContext, Html, Head, Main, NextScript, DocumentInitialProps, } from "next/document"; declare type NewDocumentInitialProps = DocumentInitialProps &amp; { userCurrency?: string; }; export default class CustomDocument extends Document { static async getInitialProps( ctx: DocumentContext ): Promise&lt;NewDocumentInitialProps&gt; { const initialProps = await Document.getInitialProps(ctx); return {...initialProps, ...{ userCurrency: "USD" }, }; } render(): JSX.Element { return ( &lt;Html&gt; &lt;Head&gt; { &lt;&gt; &lt;link rel="icon" href="/favicon_dev.svg" type="image/svg+xml" /&gt; &lt;/&gt; } &lt;/Head&gt; &lt;body data-currency={this.props.userCurrency}&gt; &lt;Main /&gt; &lt;NextScript /&gt; &lt;/body&gt; &lt;/Html&gt; ); } }</pre></div></renderpageresult> - How to extend DocumentInitialProps properly, while it shows error "Property does not exist on type Readonly<RenderPageResult ReactElement"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型“ Readonly &lt;{}&gt;”上不存在属性“ xxx” - Property 'xxx' does not exist on type 'Readonly<{}>' 属性 &#39;google&#39; 不存在于类型 &#39;Readonly&lt;{ IGoogleMapTrackerProps }&gt; &amp; Readonly&lt;{ chirldren?: ReactNode; }&gt;&#39; - Property 'google' does not exist on type 'Readonly<{ IGoogleMapTrackerProps }> & Readonly<{ chirldren?: ReactNode; }>' 属性 &#39;XYZ&#39; 不存在于类型 &#39;Readonly&lt;{ children?: ReactNode; }&gt; 和只读&lt;{}&gt;&#39; - Property 'XYZ' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' 类型“IntrinsicAttributes 和 IntrinsicClassAttributes”上不存在属性“名称”<product> &amp; 只读&lt;{}&gt;'</product> - Property 'name' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Product> & Readonly<{}>' “只读”类型上不存在属性“路由器” <props & routecomponentprops<{}, staticcontext, poormansunknown> &gt;</props> - Property 'router' does not exist on type 'Readonly<Props & RouteComponentProps<{}, StaticContext, PoorMansUnknown>> 打字稿错误属性 x 在类型“只读”上不存在<Props> &amp; Readonly&lt;{ children?: ReactNode; }&gt;&#39; - Typescript error Property x does not exist on type 'Readonly<Props> & Readonly<{ children?: ReactNode; }>' vue-apollo - 类型“只读”上不存在属性“值” <ref<readonly<any> &gt;&gt;' </ref<readonly<any> - vue-apollo - Property 'value' does not exist on type 'Readonly<Ref<Readonly<any>>>' this.state.someProp 在 ReadOnly 类型上不存在 - this.state.someProp Does Not Exist on type ReadOnly React Class 组件属性中的 TypeScript 错误在类型“Readonly&lt;{}&gt;”上不存在,不确定如何为 state 设置类型 - TypeScript errors in React Class Component property does not exist on type 'Readonly<{}>', not sure how to set types for state 如何正确扩展 DocumentInitialProps,同时显示错误“只读类型上不存在属性<renderpageresult reactelement"< div><div id="text_translate"><p> 我是 Typescript 的初学者。 我正在研究 Nextjs Typescript 项目。 基本上,我想要做的是通过body标签将userCurrency值从服务器端传递给客户端。 我正在处理_document.tsx文件。 问题是我收到了这个错误</p><p><a href="https://i.stack.imgur.com/sX2Np.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sX2Np.png" alt="在此处输入图像描述"></a></p><p> 我从错误消息中收集到的是DocumentInitialProps上不存在userCurrency ,并且参考其他 stackoverflow 帖子我正在尝试将附加属性userCurrency扩展/添加到DocumentInitialProps 。 我在这里试过了,忽略黄色条..</p><p> <a href="https://i.stack.imgur.com/9O5kl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9O5kl.png" alt="在此处输入图像描述"></a></p><p> 如您所见,我创建了NewDocumentInitialProps 。 但是,错误仍然存在。 我究竟做错了什么? 如何向DocumentInitialProps添加自定义属性?</p><pre> import { Fragment } from "react"; import Document, { DocumentContext, Html, Head, Main, NextScript, DocumentInitialProps, } from "next/document"; declare type NewDocumentInitialProps = DocumentInitialProps &amp; { userCurrency?: string; }; export default class CustomDocument extends Document { static async getInitialProps( ctx: DocumentContext ): Promise&lt;NewDocumentInitialProps&gt; { const initialProps = await Document.getInitialProps(ctx); return {...initialProps, ...{ userCurrency: "USD" }, }; } render(): JSX.Element { return ( &lt;Html&gt; &lt;Head&gt; { &lt;&gt; &lt;link rel="icon" href="/favicon_dev.svg" type="image/svg+xml" /&gt; &lt;/&gt; } &lt;/Head&gt; &lt;body data-currency={this.props.userCurrency}&gt; &lt;Main /&gt; &lt;NextScript /&gt; &lt;/body&gt; &lt;/Html&gt; ); } }</pre></div></renderpageresult> - How to extend DocumentInitialProps properly, while it shows error "Property does not exist on type Readonly<RenderPageResult ReactElement"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM