如何解决尝试访问 AVPlaybackStatus 的错误属性时出错
我是 TypeScript 的新手,正在尝试使用 expo-av 进行音频播放。
以下代码给了我一个错误:TS2339: Property 'error' does not exist on type 'AVPlaybackStatus'.
const { sound,status } = await Audio.Sound.createAsync(track.mp3);
if (status.isLoaded) {
console.info(status.durationMillis);
}
else {
console.error("track not loaded",status.error);
}
我查看了 status
的定义,发现:
export type AVPlaybackStatus =
| {
isLoaded: false;
androidImplementation?: string;
error?: string; // populated exactly once when an error forces the object to unload
}
| {
isLoaded: true;
androidImplementation?: string;
uri: string;
progressUpdateIntervalMillis: number;
durationMillis?: number;
positionMillis: number;
playableDurationMillis?: number;
seekMillisToleranceBefore?: number;
seekMillisToleranceAfter?: number;
shouldPlay: boolean;
isPlaying: boolean;
isBuffering: boolean;
rate: number;
shouldCorrectPitch: boolean;
volume: number;
isMuted: boolean;
isLooping: boolean;
didJustFinish: boolean; // true exactly once when the track plays to finish
};
我以前从未见过这个结构,但我猜这是一个 union or intersection type (?)。
我如何访问 status.error
?处理此类类型的典型习语/构造是什么?
解决方法
模式是判别联合 (docs),其中 TypeScript 可以根据一个字段来准确确定类型,该字段对于每个替代项都是不同的。在这种情况下,它是 isLoaded
布尔字段,但要使其正常工作,您确实需要启用 strictNullChecks
。除此之外,您处理它的方式完全没问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。