【问题标题】:How to define properties conditionally according to the conditional types for typescript interfaces如何根据打字稿接口的条件类型有条件地定义属性
【发布时间】:2021-07-26 08:54:27
【问题描述】:

假设我有一个在代码库中使用的现有 typescript 接口

interface example<condition extends true | false = false> {
  a: string;
  b: string;
  c: condition extends true ? string : number;
  // many other properties
}

现在如果条件为真,我想保留属性 a,但如果条件为假,则将属性 a 替换为属性 d,怎么能我做吗?

是否有任何简单的方法,例如 javascript 对象如何使用它,如下所示(虽然有语法错误)

interface example<condition extends true | false = false> {
  ...(condition extends true && {a: string});
  ...(condition extends false && {d: string});
  b: string;
  c: condition extends true ? string : number;
  // many other properties
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你可以使用下一个类型:

    type Example<Condition extends boolean = false> = Condition extends true ? {
        a: string;
        b: string;
        c: string;
    } : {
        d: string;
        b: string;
        c: number;
    }
    

    Playground

    根据 TS 约定,类型和接口应该使用 CamelCase。

    另外,true | false 只是一个boolean

    【讨论】:

    • 谢谢!一个问题是还有许多其他属性不受 Condition 影响,所以这样我必须写两次,这对我来说有点多余。
    【解决方案2】:

    找到解决办法

    type Example<Condition extends boolean = false> = {
        b: string;
        c: string;
        e: string;
        f: string;
        g: string;
        h: string;
        i: string;
    } & (Condition extends true ? {
        a: string;
    } : {
        d: string;
    })
    

    无论如何都可以通过使用接口来做到这一点?

    【讨论】:

    • 是的,可以这样做
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2016-08-29
    • 1970-01-01
    • 2019-05-03
    • 2022-12-18
    • 1970-01-01
    相关资源
    最近更新 更多