#Improve class typing

4 messages · Page 1 of 1 (latest)

tranquil marshBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
  • Marked as resolved by OP
hazy pilot

you can't

candid pond

You can have 2 classes

class StartedMatch {
  public constructor(public data: MatchData) {}
}

class UnstartedMatch {
  public async start() {
    const data = await create();
    return new StartedMatch(data);
  }
}

type Match = StartedMatch | UnstartedMatch;

let match: Match = new UnstartedMatch();
match = await match.start();

match.data

Another way with an interface

interface StartedMatch {
  data: MatchData;
}

class Match {
  public constructor(public data?: MatchData) {}

  public async start() {
    const data = await create();
    return new StartedMatch(data);
  }

  public isStarted(): this is StartedMatch {
    return typeof this.data !== 'undefined';
  }
}

const match = new Match();
await match.start();

if (match.isStarted()) {
  match.data;
}