打字稿:需要另一个参数时需要参数

时间:2020-11-01 16:15:43

标签: typescript

我有一个接口,仅当ca时才需要true参数。

interface IArgs {
  a: boolean,
  b: string,
  c: string
}

以下内容似乎有效,但是如何在第一个子句中忽略c参数?使用type是因为interface会返回错误。

type TArgs = {
  a: true,
  b: string,
  c?: string
} | {
  a: false,
  b: string,
  c: string
};

1 个答案:

答案 0 :(得分:1)

这可能是您要寻找的。但是您必须显式设置TArgs<true>

type TArgs<T extends boolean> = {
   a: T,
   b: string,
   c: T extends true ? string : null
 }

使用工厂功能的外观示例:

type TArgs<T extends true | false> = {
    a: T,
    c?: T extends true ? string : null
}

const argsFactory = <T extends boolean>(a: T, c: T extends true ? string : null): TArgs<T> => {
    return {
        a,
        c
    }
}

// Works
argsFactory(true, "string");
argsFactory(false, null);

// Doesnt Work
argsFactory(false, "some String");
argsFactory(true, null)
相关问题