why TypeScript's typeof keyword just get the literal type?

146 views Asked by At

here is some ts code:

type TopRoomInfoState = {
  loaded: false;
  loading: boolean;
  error: any;
  data: null;
} | {
  loaded: true;
  loading: boolean;
  error: any;
  data: GetTopRoomInfoRsp;
}

const inititalState: TopRoomInfoState = {
  loaded: false,
  loading: false,
  error: null,
  data: null,
};

type Test = typeof inititalState;
// but this `type Test` is merely the literal type of `const inititalState`
// not the whole union TopRoomInfoState ...

and why the type Test is the subset of the union TopRoomInfoState ?? how to make type Test is whole the union type ?

enter image description here

1

There are 1 answers

0
Mahdi Ghajary On

Because You have given Typescript hints that which one of the types forming TopRoomInfoState is your initialState variable.

If the loaded property of objects is false then your object is either of type

{
  loaded: false;
  loading: boolean;
  error: any;
  data: null;
}

or it's not of type TopRoomInfoState altogether. the same is true if your data property is of type GetTopRoomInfoRsp, then your object surely can't be of type

{
  loaded: false;
  loading: boolean;
  error: any;
  data: null;
}

This is called Type narrowing in typescript. I suggest looking it up in TS docs and also Discriminating Unions.