试图访问AVPlaybackStatus的Error属性时出错



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

我以前从未见过这个结构,但我猜这是一个联合或交叉类型(?)。

如何访问status.error?使用这种类型的典型习语/结构是什么?

该模式是判别联合(docs), TypeScript可以根据一个字段准确地确定类型,该字段对于每个备选项都是不同的。在本例中,它是isLoaded布尔字段,但要使其工作,您确实需要启用strictNullChecks。除此之外,你处理它的方式完全没问题。

最新更新