区分函数参数是否可选

时间:2019-09-04 05:14:36

标签: typescript

如何区分函数参数是否可选?

如何区分

(p?: string): object

(p: string): object

我尝试过

type A = {
  (p?: string): object
}
type B<A> = A extends (p: string | undefined) => object ? string : number
type C = B<A>

但这不起作用

有什么办法可以区分它们吗? 谢谢。

2 个答案:

答案 0 :(得分:2)

您可以通过使用条件类型来测试您的函数是否可分配给具有可选第一个参数的另一个函数来执行此操作。像这样:

type A = {
  (p?: string): object
}

type B = {
    (p: string): object
}

type OptionalFirstArg = (a?: never) => unknown;

type IsOpt<F> = F extends OptionalFirstArg ? true : false;

type testA = IsOpt<A>; // testA is true
type testB = IsOpt<B>; // testB is false

上面的代码是playground link

答案 1 :(得分:1)

当不存在参数时,可以通过检查() => object来区分。

type A1 = {
  (p?: string): object; // optional input parameter
}
type A2 = {
  (p: string): object; // required input parameter
}
type B<T extends (p: string) => object> =
  T extends () => object ?
    number
    : T extends (p: string) => object
    ? string
    : never;

type C1 = B<A1>; // number
type C2 = B<A2>; // string