首页 > 解决方案 > 如何根据打字稿接口的条件类型有条件地定义属性

问题描述

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

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

解决方案


找到了解决方案

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

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


推荐阅读