【问题标题】:Conditional types inside interface接口内的条件类型
【发布时间】:2021-07-07 08:42:23
【问题描述】:

我有一个这个形状的接口

interface MyInterface {
    otherVal1: string;
    otherVal2: string;
    ...;
    container: 'bank' | 'creditCard' | 'investment'
    type: 'option1' | 'option2' | 'option3' ...
} 

我需要根据 container 属性为 type 属性设置类型。 例如,如果容器值为 bank,则 type 的选项例如是 option1option2。如果是creditCard,选项有option3option4option5等等。

我在文档和 StackOverflow 上都找不到与我的案例类似的任何实现。

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    你会使用union type:

    type MyInterface =
        {container: "bank", type: "option1" | "option2"}
        |
        {container: "creditCard", type: "option3" | "option4" | "option5"}
        |
        {container: "investment", type: "option6" | "option7"}
    ;
    

    使用它时,您将使用类型保护检查 container,以便 TypeScript 知道 type 的有效类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多