【问题标题】:Types of optional and default parameters in typescript打字稿中可选参数和默认参数的类型
【发布时间】:2021-06-21 07:26:37
【问题描述】:

假设我正在创建一个可以返回唯一参数本身的函数,在 javascript 中它会是这样的:

function returnItself(x) {
  return x;
}

而且我还想保持参数的类型不变,让参数可选,所以我写了:

function returnItself<T>(x?: T) {
  return x;
}

但结果是……

var a1 = returnItself("foo");
type A1 = typeof a1; // expect A1 to be "string", but it's "string | undefined".
var a2 = returnItself();
type A2 = typeof a2; // expect A2 to be "undefined", but it's "{} | undefined".

我尝试将可选参数更改为默认值:

function returnItself<T extends any>(x: T = 0 as number) {
  return x; // if x is not given it should return number 0;
}

但甚至出现编译器错误:

Type 'number' is not assignable to type 'T'.

写这个的正确方法是什么?

***** 编辑 ****

在这种情况下:

function returnItself<T>(x?: T) {
  return x;
}
var a1 = returnItself(undefined); // a1 = undefined. ok
var a2 = returnItself(); // a2 = undefined. ok
type A1 = typeof a1; // type A1 = undefined. ok
type A2 = typeof a2; // type A2 = {} | undefined. ???

如果我清楚地将 undefined 作为参数传递,Typescript 可以正确推断返回类型。

但是,当我不给出参数时,我希望得到与上述相同的结果(和类型),但它们的结果类型不一样。

我相信returnItself()returnItself(undefined) 应该有相同的行为,也许我错了?

====== 2 年后,我找到了最佳答案:

function returnItself<T = undefined>(x?: T): T {
  return x as T;
}

【问题讨论】:

  • 您不能将number 类型的默认值设置为T 类型的参数。由于类型在运行时被擦除,因此您无法真正做出运行时决定(即基于T 分配给x 的默认值)

标签: typescript


【解决方案1】:

可选意味着它可以是undefinednull。所以返回类型是正确的。

如果你不希望它为空,那么只需使用

function returnItself<T>(x: T) {
  return x;
}

T 也是泛型类型,这意味着它可以是任何东西。你不能强迫它成为number

【讨论】:

    【解决方案2】:

    您不能将number 分配给T,因为它对编译器没有意义。基本上,T 是一个泛型类型,您在这里将它用作变量。这意味着调用此函数的用户可以说出T 在运行时应该是什么类型:

    const a1 = returnItself<number>(9) 
    

    因此,当您将 number 分配给 T 时,打字稿会抱怨,因为它还不知道 T 是什么。如果您想使用 TypeScript 中的可选值,我建议养成明确检查该值是否存在于函数体中的习惯。以下将通过您的所有测试:

    function returnItself<T>(x?: T) {
      if (x) return x
      else return 0 //or whatever other value you want as a default case
    }
    

    【讨论】:

    • 我同意,虽然我觉得 OP 从这个函数中寻找的东西也有点令人困惑,所以我在有限的理解下尽了最大的努力。我很高兴听到任何关于我为什么错的批评或解释
    • 我也不清楚意图是什么。我相信他想要一个基于T 的默认值,如果没有其他参数,这是不可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2019-10-15
    • 2021-05-26
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多