【问题标题】:TypeScipt properties dependent on boolean?TypeScript 属性依赖于布尔值?
【发布时间】:2021-07-21 15:51:01
【问题描述】:

打字稿中有没有一种方法可以使接口依赖于该接口中某些东西的值?我想要做的是我有一个可以选择关闭的盒子,而且无论我们是否存储该动作以使其持久化,它也是可选的,所以我有一个这样的界面:

interface ButtonProps = { closable: boolean, closableKey?: string }

如果 closable 为 false,我不希望人们能够设置 closableKey,反之亦然。 TypeScript 可以做到吗?

【问题讨论】:

    标签: typescript interface


    【解决方案1】:

    您可以使用union type

    type ButtonProps = {
        closeable?: false;
    } | {
        closeable: true;
        closeableKey: string;
    };
    

    这将导致以下示例中显示的(非)错误:

    【讨论】:

    • 您使用了 Union 类型并提到了 Intersection 类型。请更正
    【解决方案2】:

    你可以使用联合类型

    type ButtonProps = {
        closable: false;
    } | {
        closable: true;
        closableKey: string;
    }
    
    const props1: ButtonProps = {
        closable: true,
        closableKey: "",
    };
    
    const props2: ButtonProps = {
        closable: false,
    };
    
    

    如果您有想要包含在两者中的通用道具,您可以将您的类型与交集类型结合起来

    type GeneralProps = {
        name?: string;
    }
    
    type NotClosable = {
        closable: false;
    } & GeneralProps;
    
    type Closable = {
        closable: true;
        closableKey: string;
    } & GeneralProps;
    
    type ButtonProps = NotClosable | Closable;
    
    const props1: ButtonProps = {
        closable: true,
        closableKey: "",
    };
    
    const props2: ButtonProps = {
        closable: false,
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      相关资源
      最近更新 更多