Reputation: 56
Let me explain: you have a class Player. In Player, you have two getters: isPlaying: boolean
& current: AudioResource | undefined
. What I want to do is to make current
return type 100% AudioResource
, without undefined if isPlaying
is 100% true. I saw it in some projects but I don't know how to do it
Upvotes: 0
Views: 146
Reputation: 33901
You can create user-defined type guard functions to determine (at runtime) whether the player is active and has the audio resource or not. Here's an example:
// You didn't show this type, so here's an example:
type AudioResource = {
readable: ReadableStream;
};
// The `Player` class you described:
declare class Player {
get current (): AudioResource | undefined;
get isPlaying (): boolean;
}
// Type guards:
type PlayerActive = {
current: AudioResource;
isPlaying: true;
};
function isActive (player: Player): player is PlayerActive {
return player.isPlaying;
}
type PlayerInactive = {
current: undefined;
isPlaying: false;
};
function isInactive (player: Player): player is PlayerInactive {
return !player.isPlaying;
}
// Usage example:
const player = new Player();
player.current;
//^? (property) Player.current: AudioResource | undefined
player.isPlaying;
//^? (property) Player.isPlaying: boolean
if (isActive(player)) {
player.current;
//^? (property) current: AudioResource
player.isPlaying;
//^? (property) isPlaying: true
}
if (isInactive(player)) {
player.current;
//^? (property) current: undefined
player.isPlaying;
//^? (property) isPlaying: false
}
Upvotes: 2