Home > OS >  typescript conditional types inner types
typescript conditional types inner types

Time:12-21

I have the following type defined:

export type Limited = {
    multiple: boolean;
    trunk: Limited['multiple'] extends true ? true : false;
};

I want the trunk property to be limited my the multiple property. The current approach makes trunk to always be false.

I can't fathom why is that, and how to fix it.

CodePudding user response:

The type you've written says to do a type calculation based on Limited['multiple']'s type. That type is boolean. Does boolean extend from true? No, it doesn't (true extends from boolean, but not the other way around). As a result, trunk gets the type false.

If you're trying to say that multiple and trunk must either both be true, or both be false, then you'd do that like this:

export type Limited = {
  multiple: true;
  trunk: true;
} | {
  multiple: false;
  trunk: false;
}

Or alternatively you could use a generic:

export type Limited<T extends boolean> = {
  multiple: T,
  trunk: T
}
  • Related