类型“ImageSourcePropType”上不存在属性“uri”

Pdo*_*dom 5 typescript reactjs react-native

我想包装react-native的图像组件。但是,会出现一条错误消息,指出“uri”属性不存在。为什么会出现这种情况?

import React from 'react';
import { Image as DefaultImage, ImageProps } from 'react-native';
import { PromiseFn, useAsync } from 'react-async';

type ImageSize = {
  width: number;
  height: number;
};

const getImageSize = (uri: string) => {
  return new Promise<ImageSize>((resolve, reject) => {
    DefaultImage.getSize(
      uri,
      (width, height) => {
        resolve({ width, height });
      },
      (error) => {
        reject(error);
      }
    );
  });
};

const promiseFn: PromiseFn<ImageSize> = async ({ uri }) =>
  await getImageSize(uri);

export function Image(props: ImageProps) {
  const { source } = props;
  const { data, error, isPending } = useAsync<ImageSize>({
    promiseFn: promiseFn,
    uri: source.uri, // Property 'uri' does not exist on type 'ImageSourcePropType'.
                     // Property 'uri' does not exist on type 'number'.ts(2339)
  });

  return (
    <DefaultImage
      style={[{ width: data?.width, height: data?.height }, props.style]}
      {...props}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的方法,但还有另一个错误。

const isImageURISource = (
  source: ImageURISource | ImageURISource[] | ImageRequireSource
) => {
  if ('uri' in source) {
    return source; // The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
  }
};
Run Code Online (Sandbox Code Playgroud)

Gol*_*Jer 0

我不确定这是一个很好的解决方案,但这就是我解决同样问题的方法。
基本上重写了source类型。

import {
  ImageProps as DefaultImageProps,
  ImageURISource,
} from 'react-native';

type ImageProps = DefaultImageProps & {
  source: ImageURISource;
};
Run Code Online (Sandbox Code Playgroud)