简体   繁体   English

同一接口中的条件属性

[英]Conditional property in the same interface

I was wondering if what I'm trying to do here is possible in TS:我想知道我在这里尝试做的事情在 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: ... 
} 
: {};

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 .这将确保directoryPaths只能在commandParsingModecustom时出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM