Home > database >  Conditional property in the same interface
Conditional property in the same interface

Time:07-25

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: ... 
} 
: {};

CodePudding user response:

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.

  • Related