Olebeh
Olebeh

Reputation: 56

How to dynamically change function's return type that depends on earlier code?

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

Answers (1)

jsejcksn
jsejcksn

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:

TS Playground

// 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

Related Questions