我有一个具有如下形状的函数
const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code }我需要让第二个参数(对象)是可选的,可以吗?
发布于 2022-06-08 06:20:06
您可以将空对象{}指定为默认的param值。用Partial包装对象param类型,使其记忆符可选,与添加问号{ objArg?: string }相同
const func = (arg1: string, { objArg = true }: Partial<{ objArg: string | boolean }> = {}) => {
console.log(objArg)
}发布于 2022-06-08 06:30:35
您可以设置默认值,它将自动成为可选的:
const func = (
arg1: string,
{ objArg = true }: { objArg: boolean } = undefined
) => {}发布于 2022-06-08 06:17:09
如果要使参数可选,应在以下之前使用?(问号):
可选参数必须是函数的最后一个参数。有关更多信息,请查看此页面。https://www.typescripttutorial.net/typescript-tutorial/typescript-optional-parameters/
https://stackoverflow.com/questions/72540857
复制相似问题