Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional property in the same interface

I was wondering if what I’m trying to do here is possible in TS:

type CommandParsingMode = "routes" | "custom";

type Type = {
  commandParsingMode: "routes" | "custom";
  // this prop should be non-existent if "routes" is chosen
  directoryPaths: {
    ...
  }
}

I tried doing it this way, but it doesn’t seem to work.

                  // same type as above
type Props<M extends CommandParsingMode = CommandParsingMode> = BaseProps 
& {
  commandParsingMode: M;
} 
& M extends "custom" 
? { 
  directoryPaths: ... 
} 
: {};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can have composite type as follow:

type Type = {
  commandParsingMode: "routes"
} | {
  commandParsingMode: "custom";
  directoryPaths: {
    ...
  }
}

This will make sure that the directoryPaths can be only present when commandParsingMode is custom.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading