Home > Back-end >  Typescript object may be undefined
Typescript object may be undefined

Time:08-04

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;
};

CodePudding user response:

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]);
  • Related