您可以在Typescript函数中使用可选的分解结构参数吗?

时间:2018-10-16 19:59:38

标签: typescript

我想编写一个函数,该函数接受一个对象参数,在函数签名中使用解构,并使该参数为可选:

myFunction({opt1, opt2}?: {opt1?: boolean, opt2?: boolean})

但是,Typescript不允许我这样做(“绑定模式参数在实现签名中不能是可选的。”)。

如果不进行破坏,我当然可以做到:

myFunction(options?: {opt1?: boolean, opt2?: boolean}) {
  const opt1 = options.opt1;
  const opt2 = options.opt1;
  ...

似乎这些应该是同一回事,但不允许使用最高示例。

我想使用一种解构语法(1),因为它存在并且是一种不错的语法,并且上述两个函数的行为似乎很自然;(2)因为我也想要一种简洁的方法指定默认值:

myFunction({opt1, opt2 = true}?: {opt1?: boolean, opt2?: boolean})

在没有解构的情况下,我必须将这些默认值埋在函数的实现中,或者使用一个实际上是带有构造函数的类的参数...

2 个答案:

答案 0 :(得分:6)

改为使用默认参数:

function myFunction({ opt1, opt2 = true }: { opt1?: boolean; opt2?: boolean; } = {}) {
    console.log(opt2);
}

myFunction(); // outputs: true

有必要不破坏undefined

function myFunction({ opt1, opt2 }) {
}
    
// Uncaught TypeError: Cannot destructure property `opt1` of 'undefined' or 'null'.
myFunction();

答案 1 :(得分:0)

如果没有作为参数给出的对象,则无法解构。因此,在 parmas 中使用默认对象,如前一篇文章所述:

type Options = { opt1?: boolean; opt2?: boolean; }

function myFunction({ opt1, opt2 }: Options = {}) {
    console.log(opt2, opt1);
}

myFunction() // undefined,  undefined 
myFunction({opt1: false}); // undefined,  false 
myFunction({opt2: true}); // true,  undefined

我想补充的是,当满足以下 2 个条件时,params 中的这种解构模式会增加最大的价值:

  • 选项数量可能会发生变化
  • 函数的 API 可能会发生变化。即函数参数可能会改变

基本上解构为您提供了更大的灵活性,因为您可以添加任意数量的选项,而只需对函数的 API 进行最少的更改。

但是,更基本的版本会更简单:

// If the function is not likely to change often just keep it basic:
function myFunctionBasic( opt1? :boolean, opt2?: boolean ) {
    console.log(opt2, opt1);
}
相关问题