【问题标题】:Error trying to access the error property of AVPlaybackStatus尝试访问 AVPlaybackStatus 的错误属性时出错
【发布时间】:2021-05-21 17:03:52
【问题描述】:

我是 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?使用这些类型的典型习语/构造是什么?

【问题讨论】:

  • 确保在您的tsconfig.json 中启用了strictNullChecks
  • 嗯好吧,我昨天刚刚因为其他问题禁用了它。
  • 但你是对的,请转换为答案。

标签: typescript react-native expo union-types expo-av


【解决方案1】:

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

【讨论】:

  • 谢谢你的背景!
猜你喜欢
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 2016-04-19
相关资源
最近更新 更多