你能在一个类型脚本函数中使用可选的解构参数吗?

我想编写一个函数,它接受一个对象参数,在函数签名中使用解构,并且这个参数是可选的:

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

但是,Type 脚本不允许(“绑定模式参数在实现签名中不能是可选的”)。

当然,如果我不破坏的话,我可以做到这一点:

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

看起来这两个应该是一样的,但是上面的例子是不允许的。

我想使用一个非结构化语法(1) ,因为它确实存在,而且是一个很好的语法,上面两个函数的作用相同似乎是很自然的,(2)因为我还想用一种简洁的方式来指定默认值:

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

如果不重构,我必须在函数的实现中隐藏这些缺省值,或者有一个实际上是带有构造函数的类的参数..。

27811 次浏览

使用默认参数:

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();

如果没有作为参数给出的对象,则无法进行解构。因此,在 parma 中使用一个默认对象,就像前面提到的那样:

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

我想补充的是,当以下两个条件成立时,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);
}

如果希望混合使用可选参数和必需参数,但是导出的类型中所有值都是必需的/非空的,那么这是最好的方法:

export function newCar(args: {
year?: number
make?: string
model: string
owner: [string, string]
}) {
const defaults = {
year: 1999,
make: "toyota",
}
return { ...defaults, ...args }
// to get a Readonly<Car>:
// return Object.freeze(args)
}


export type Car = ReturnType<typeof newCar>


const c = newCar({ model: "corolla", owner: ["Gorg", "Blafson"] })


export function print(c: Car) {
console.log(`${c.owner}'s gorgeous ${c.year} ${c.model} from ${c.make}`)
}