Is it possible to narrow a property's return type based on another property?
For example:
type DataState = 0 | 1 | 2;
class DataClass<T extends DataState = DataState> {
private _state: T = 0 as T;
private _data?: T extends 2 ? number : undefined;
public get state() { return this._state }
public get data() { return this._data }
}
const obj = new DataClass();
obj.data // State unknown: data = number | undefined
if (obj.state === 2) obj.data // State is 2: data *should be* = number (it's not)
- Here, I have
DataState, which is 0, 1 or 2. - When I create a
new DataClass, the_stateproperty can be any one ofDataState, so the type ofdatais one ofnumber | undefined. - After checking the value of
statethough, surely this would be enough to know the type ofdataas a number, no?
I'm not sure if I'm doing something wrong, or this type of thing just isn't really possible