Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript object may be undefined

I’m new to Typescript. I can’t build because of that error and I can’t find the right solution to solve it

useAudio.tsx

import { useEffect, useRef } from 'react';

type Options = {
  volume: number;
  playbackRate: number;
};

const useAudio = (src: string, { volume = 1, playbackRate = 1 }: Options) => {
  const sound = useRef(
    typeof Audio !== "undefined" ? new Audio(src) : undefined
    );

  useEffect(() => {
    if (Audio !== undefined) {
    sound.current.playbackRate = playbackRate;
    }
  }, [playbackRate]);
  useEffect(() => {
    sound.current.volume = volume;
  }, [volume]);

  return sound.current;
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As per error, sount.current might be undefined. due to typeof Audio !== "undefined" ? new Audio(src) : undefined. So when it is undefined – you cant set undefined.playbackRate.

  useEffect(() => {
    if (Audio !== undefined) {
      if (sound.current) sound.current.playbackRate = playbackRate;
    }
  }, [playbackRate]);

  useEffect(() => {
    if (sound.current) sound.current.volume = volume;
  }, [volume]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading