如何根据打字稿接口的条件类型有条件地定义属性

时间:2021-07-26 08:54:27

标签: typescript

假设我在代码库中使用了一个现有的 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
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

找到解决办法

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;
})

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