Home > Software design >  Argument of type 'Sound' is not assignable to parameter of type 'SetStateAction<un
Argument of type 'Sound' is not assignable to parameter of type 'SetStateAction<un

Time:10-17

I'm writing a simple react-native app using typescript and expo-cli. I've imported expo-av but I'm having some trouble when trying to play audio. I'm following [this guide][1] but it's written in javascript and I guess that's the problem here since it's complaining about types.

  import { Audio } from "expo-av";
  
  export const useAudio = () => {
    const [sound, setSound] = useState();

    const playSound = async () => {
        const { sound } = await Audio.Sound.createAsync( // this line causes the error
        require("../assets/sound/ding.mp3")
      );
    setSound(sound);
    await sound.playAsync();
  }
};

[![error message][2]][2]


  [1]: https://docs.expo.dev/versions/v42.0.0/sdk/audio/
  [2]: https://i.stack.imgur.com/PqDgC.png

CodePudding user response:

Since you are initializing sound state as undefined (useState()), Typescript doesn't allow setting sound to any other type.

I suggest you type sound like this:

    const [sound, setSound] = useState<Audio.Sound|null>(null);

So, sound is null initially but may be set to another object of type Audio.Sound based on the logic of the component. which requires you to always be careful whether sound is null or not before using any of its properties.

for example:

sound.play() // first check if it isn't null!
  • Related