如何根据isPlaying状态动态调整Player类current getter的返回类型?
实现 Player 类的状态-资源类型关联
要让isPlaying为true时current自动收窄为AudioResource(排除undefined),核心是让TypeScript识别两个属性的类型关联,下面是两种常用实现方式:
方法一:用区分联合类型(Discriminated Union)
直接将Player定义为两种状态的联合类型,利用TypeScript的自动类型收窄特性:
// 先定义你的 AudioResource 类型 type AudioResource = { duration: number; src: string; // 其他音频资源属性 }; // 空闲状态的 Player type IdlePlayer = { isPlaying: false; current: undefined; }; // 播放状态的 Player type PlayingPlayer = { isPlaying: true; current: AudioResource; }; // 联合类型:自动关联状态与资源类型 type Player = IdlePlayer | PlayingPlayer; // 使用示例 const randomPlayer: Player = Math.random() > 0.5 ? { isPlaying: true, current: { duration: 100, src: "audio.mp3" } } : { isPlaying: false, current: undefined }; if (randomPlayer.isPlaying) { // 此处 TypeScript 自动推断 current 为 AudioResource,无 undefined console.log(randomPlayer.current.duration); } else { // 此处 current 为 undefined console.log("No audio playing"); }
方法二:保留类结构,用自定义类型守卫
如果需要保留类的封装(比如私有属性、方法),可以通过自定义类型守卫函数告诉TypeScript两个getter的关联关系:
type AudioResource = { duration: number; src: string; }; class Player { private _isPlaying = false; private _current: AudioResource | undefined; get isPlaying(): boolean { return this._isPlaying; } get current(): AudioResource | undefined { return this._current; } // 自定义类型守卫:断言当前实例处于播放状态时,current 必为 AudioResource isPlayingWithResource(): this is { isPlaying: true; current: AudioResource } { return this._isPlaying && this._current !== undefined; } // 示例方法:开始播放 play(resource: AudioResource) { this._isPlaying = true; this._current = resource; } // 示例方法:停止播放 stop() { this._isPlaying = false; this._current = undefined; } } // 使用示例 const player = new Player(); player.play({ duration: 100, src: "audio.mp3" }); if (player.isPlayingWithResource()) { // 此处 current 自动收窄为 AudioResource console.log(player.current.src); }
内容的提问来源于stack exchange,提问作者Olebeh
相关产品推荐
相关产品推荐

