You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native+TS+Expo使用expo-av播放音频出现类型报错如何解决?

报错解决方案

报错原因

该类型报错是由于未显式指定React状态的类型导致的类型不匹配:你初始化useState()时未传初始值也没有指定泛型,TypeScript自动推导sound状态的类型为undefined,后续调用setSound传入expo-av的Sound类型实例时,二者类型不匹配就触发了该错误。

修复步骤

  • 从expo-av包中导入Sound类型
  • 给useState添加泛型声明,指定状态类型为Sound | undefined(初始状态为空)
  • 可选优化:解构创建的音频实例时重命名变量,避免和外层状态重名造成逻辑混淆

修复后完整代码

import { Audio, Sound } from "expo-av";
import { useState, useEffect } from "react";

export const useAudio = () => {
  // 显式指定状态的类型
  const [sound, setSound] = useState<Sound | undefined>();

  const playSound = async () => {
    const { sound: newSound } = await Audio.Sound.createAsync(
      require("../assets/sound/ding.mp3")
    );
    setSound(newSound);
    await newSound.playAsync();
  };

  // 补充卸载时的资源释放逻辑,避免内存泄漏
  useEffect(() => {
    return () => {
      sound?.unloadAsync();
    };
  }, [sound]);

  return { playSound };
};

内容的提问来源于stack exchange,提问作者Mangs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:48:02