【问题标题】:Type '(oldPlacePhotos: string[]) => string[]' is missing the following properties from type 'string[]': pop, push, concat, join, and 28 more类型 '(oldPlacePhotos: string[]) => string[]' 缺少来自类型 'string[]' 的以下属性:pop、push、concat、join 等 28 个
【发布时间】:2022-01-24 05:39:59
【问题描述】:

这辈子都想不通。

这是代码示例

Parent.tsx

  const [placePhotos, setPlacePhotos] = useState<string[]>([])

  ...
  useEffect(() => foo(setPlacePhotos), [])

helper.ts where foo() 存在

type GooglePlaceInfoObject = {
  setPlacePhotos?: (photos: Array<string>) => string[]
}

foo({ setPlacePhotos }: GooglePlaceInfoObject) {
        if (setPlacePhotos) {
          // this returns an array of strings
          const photosArray = googlePlaceDetailsObject.photos.map(photo => {
            return photo.getUrl({
              maxWidth: 320,
              maxHeight: 426,
            })
          })
          // error happens here!
          setPlacePhotos((oldPlacePhotos: string[]) => [
            ...oldPlacePhotos,
            ...photosArray,
          ])
        }
}

使用时出错 setPlacePhotos

Argument of type '(oldPlacePhotos: string[]) => string[]' is not assignable to parameter of type 'string[]'.
  Type '(oldPlacePhotos: string[]) => string[]' is missing the following properties from type 'string[]': pop, push, concat, join, and 28 more.

你如何解决这个错误?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您的自定义GooglePlaceInfoObject 类型不必要地限制了setPlacePhotos 的类型,因此它不支持functional form of setState。要解决此问题,您可以将其更改为:

    type GooglePlaceInfoObject = {
      setPlacePhotos?: (photos: string[] | ((oldPhotos: string[]) => string[])) => void
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-29
      • 2021-07-15
      • 2018-03-03
      • 1970-01-01
      • 2021-02-04
      • 2019-12-28
      • 1970-01-01
      • 2021-10-01
      • 2021-10-02
      相关资源
      最近更新 更多