简体   繁体   中英

TypeScript Props as Array of Objects or string

I will receive a props url that could be string or array of objects like:

type VideoSrcProps = {
    url?: string;
    day?: string;
  };
  interface OwnProps {
    url: VideoSrcProps[] | string;
  }

But my implementation doesn't work because I receive Property 'url' does not exist on type 'string | VideoSrcProps' Property 'url' does not exist on type 'string' Property 'url' does not exist on type 'string | VideoSrcProps' Property 'url' does not exist on type 'string'

How it should be changed?

More code:

I'm checking that what will came array of string like

const srcIsArray = Array.isArray(url) ? true : false;
const notSingleArrayVideo = srcIsArray && url.length > 1 ? true : false;

And then

useEffect(() => {
    const preloadVideos = async () => {
      if (srcIsArray && notSingleArrayVideo) {
        const preloadedVideos = [];
        for (const video of url) {
          const response = await axios({
            url: video?.url,
            method: 'GET',
            responseType: 'blob',
          });
          const downloadedVideo = window.URL.createObjectURL(new Blob([response.data]));
          preloadedVideos.push({ url: downloadedVideo });
        }

        if (preloadedVideos.length === url.length) {
          setPreloadedVideos(preloadedVideos);
        }
      }
    };
    if (srcIsArray && notSingleArrayVideo) {
      preloadVideos();
    }
  }, []);

The problem is with url: video?.url

You have an error on this:

const notSingleArrayVideo = srcIsArray && url.length > 1? true: false;

TS will not narrow your type when using a stored value out of a ternary .

You should use the condition directly in your if statement, or do an if and return.

type VideoSrcProps = {
    url?: string;
    day?: string;
  };


interface OwnProps {
  url: VideoSrcProps[] | string;
}


function test (url: OwnProps) {
  if (Array.isArray(url.url)) {
    for (const video of url.url) {
      console.log(video.url);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM