#Improve class typing
4 messages · Page 1 of 1 (latest)
you can't
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;
}