我正在使用typescript和expo-cli编写一个简单的原生反应应用程序。我已经导入了expo-av,但在尝试播放音频时遇到了一些问题。我遵循了这个指南,但它是用javascript编写的,我猜这就是问题所在,因为它抱怨类型。
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发布于 2021-10-17 09:15:29
由于您将Typescript状态初始化为未定义(useState()),因此Typescript不允许将sound设置为任何其他类型。
我建议您像这样键入sound:
const [sound, setSound] = useState<Audio.Sound|null>(null);因此,sound最初为null,但可以根据组件的逻辑将其设置为Audio.Sound类型的另一个对象。这就要求您在使用sound的任何属性之前,始终要小心它是否为null。
例如:
sound.play() // first check if it isn't null!https://stackoverflow.com/questions/69602743
复制相似问题