我一辈子都想不出这个。
以下是的代码示例
Parent.tsx
const [placePhotos, setPlacePhotos] = useState<string[]>([])
...
useEffect(() => foo(setPlacePhotos), [])
helper.ts其中存在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.
如何修复此错误?
您的自定义GooglePlaceInfoObject
类型不必要地限制了setPlacePhotos
的类型,因此它不支持setState的函数形式。要解决此问题,您可以将其更改为以下内容:
type GooglePlaceInfoObject = {
setPlacePhotos?: (photos: string[] | ((oldPhotos: string[]) => string[])) => void
}