T
T
TheSnegok2021-07-07 18:05:21
typescript
TheSnegok, 2021-07-07 18:05:21

Array typing for a function and type change when comparing?

Hi all!
The code:

interface PropImage {
  gif: undefined | object,
  lang: string,
  key: number,
};

const Image = ({ gif, lang, key }: PropImage) => {
  
  const [loader, setLoader] = useState<boolean>(false);

  const clickCopy = (elem: any) => {
    navigator.clipboard.writeText(elem);
  };

  const loadImage = () => {
    setLoader(true);
  };

  const [setRef, visible] = useOnScreen({ rootMargin: "0px"});

  
  return (				
    <div className={s.wrapper} key={key} ref={setRef}>
      <div
        className={s.image}
        data-title={lang === 'en' ? 'Click to copy the link to the gif' : 'Нажмите чтобы скопировать ссылку на гиф'}
      >
        <picture className={visible ? s.showPicture : s.nonePicture}>
          <source type="image/webp" />
          <img
            src={gif.images.preview_webp.url === undefined ? gif.images.downsized_large.url : gif.images.preview_webp.url}
            alt={gif.slug}
            key={gif.id}
            className={!loader ? s.gifNone : s.gif}
            onClick={() => clickCopy(gif.images.original.url)}
            onLoad={() => loadImage()}
            crossOrigin="anonymous"
            width="361"
            height="203"
          />
        </picture>
      </div>

      {!loader && <div className={s.loader}></div>}
    </div>
  );
};

1. In the interface, I wrote that gifs should accept undefined or object, but it gives an error that gif and what's inside is undefined: Object is possibly 'undefined' and Property 'images' does not exist on type 'object'.
2. Here is such an interesting construction:
const [setRef, visible] = useOnScreen({ rootMargin: "0px"});*
I don't know how to add setRef: , visible: boolean topic plz)
* - (I don't understand how variables are passed from the array to the hook, I would be grateful if you could tell me or send me a link to the article)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-07-07
@TheSnegok

1. returnPut it before and it will get better.) Actually, the essence is logical: you yourself wrote that gif can be , trying to get the property y ( ) is an obvious mistake. You must process such a case in advance and take action. in modern ts it just means without any properties. If you need any object with any properties, then use . However, for good , there should not be any, you should clearly describe the structure of the resulting object. 2. Nothing is clear. is a non-standard hook. Implementations in Google are full of different ones. So bring his code and say what you want to achieve from it. if(!gif) return null;
object{}Record<string, any>any
useOnScreen

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question