#Narrow return type based on another property

5 messages · Page 1 of 1 (latest)

patent depot
#

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 _state property can be any one of DataState, so the type of data is one of number | undefined.
  • After checking the value of state though, surely this would be enough to know the type of data as a number, no?

I'm not sure if I'm doing something wrong, or this type of thing just isn't really possible

tough hemlock
#
type Data =
  | { state: 0 }
  | { state: 1 }
  | { state: 2, data: number }

declare const obj: Data
if (obj.state === 2) obj.data
//                       ^?
#

hmm, bot is dead i guess. look here: