具有基于另一个参数的默认参数的函数

d_invitable

鉴于此JavaScript函数:

function foo({ a, b, c = a + b }) {
  return c * 2;
}

当我尝试用打字稿中的类型注释它时:

function foo({ a, b, c = a + b }: { a?: number, b?: number, c: number }): number {
  return c * 2;
}

我得到错误:TS2532 Object is possibly undefined这很有意义,因为我还没有告诉过它,a并且bc未指定时不是可选的

但是,任何尝试指定此方法均无效:

  1. 重载(1):
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number;
function foo({ c }: { c: number }): number {
  return c * 2;
}

TS2371: A parameter initializer is only allowed in a function or constructor implementation.

  1. 重载(2):
function foo({ c }: { c: number }): number;
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number {
  return c * 2;
}

TS2394: This overload signature is not compatible with its implementation signature.

这对我来说没有意义,我看不出为什么TypeScript认为它们不兼容。

  1. 有条件的
function foo({
  a,
  b,
  c = a + b,
}: {
  a: typeof c extends number ? void : number;
  b: typeof c extends number ? void : number;
  c: typeof a extends number ? void : typeof b extends number ? void : number;
}): number {
  return c * 2;
}

TS2502: 'a' is referenced directly or indirectly in its own type annotation. TS2502: 'c' is referenced directly or indirectly in its own type annotation.

鉴于TypeScript无法解决递归问题,这是有道理的。

有谁知道如何将此功能强类型化?

注意:我非常清楚您可以将原型本身更改为具有不同的参数结构,但是这样做会失败。

杰罗姆布

这是一个使用联合类型的命题:

type AB_Defined = {
    a: number,
    b: number,
    c?: number,
}

type AB_Nullable = {
    a?: never,
    b?: never,
    c: number,
}

type FunctionParams = AB_Defined | AB_Nullable

// here I need to cheat using a! and b! to tell it cannot be undefined
function foo({ a, b, c = a! + b! }: FunctionParams) {
  return c * 2;
}

foo({ a: 3, b: 2  });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何通过指向另一个函数返回的函数的指针调用具有默认参数的函数?

将参数从一个函数传递到另一个函数,其中另一个参数在Python中具有相同的名称

调用另一个函数内具有参数类型的函数c#

将具有不同数量参数的函数传递给另一个函数C ++

使用具有另一个函数作为参数的函数:

将具有任意数量参数的任何函数传递给另一个函数

将函数参数传递给具有突变的另一个函数

调用另一个函数并有选择地保留默认参数

如何在打字稿中将参数从一个具有可变参数的函数传递到另一个具有可变参数的函数?

具有所有默认参数的显式构造函数不能从同一类的另一个构造函数调用

如何将函数传递给模板化函数A,该函数可能基于A的另一个参数而具有不同的签名?

具有另一个模板类的参数化模板类构造函数

具有可变数量和参数类型的C ++函数作为另一个函数的参数

如何在 C++ 中提供模板化函数作为另一个函数的参数,并具有默认值?

具有一个默认参数和一个变量参数的C ++构造函数

根据另一个参数定义默认参数

基于另一个参数的打字稿函数参数类型

函数参数的默认值等于另一个参数

默认的LESS函数参数最初设置为另一个参数吗?

NiceMock一个具有另一个Mock作为构造函数参数的Mock

在另一个带有点参数和默认值的函数中调用带有点参数和默认值的函数

带有参数的循环函数在另一个带有参数的循环函数中

如何从具有可选第三个参数的另一个函数调用函数?

基于另一个参数约束参数类型的最有效方法

Java从另一个构造函数调用构造函数而没有立即具有参数

返回具有多个输入参数的函数的值以在同一类中具有多个参数的另一个函数中使用?

将一个函数的所有参数传递给另一个函数

我如何将异步函数用作另一个函数的默认参数

从python字典调用具有多个参数的函数名到另一个函数