[英]how to make optional object parameter in Typescirpt?
i have a function with following shape我有以下形状的功能
const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code }
i need to make second parameter (object) optional, is it possible ?我需要使第二个参数(对象)可选,这可能吗?
You can assign an empty object {}
as default param value to it.您可以为其分配一个空对象
{}
作为默认参数值。 Wrapping object param type with Partial
to make its memebers optional, same as adding question mark { objArg?: string }
用
Partial
包装对象参数类型,使其成员可选,与添加问号{ objArg?: string }
相同
const func = (arg1: string, { objArg = true }: Partial<{ objArg: string | boolean }> = {}) => {
console.log(objArg)
}
You can set an default value and it will be automatically optional:您可以设置一个默认值,它将自动成为可选的:
const func = (
arg1: string,
{ objArg = true }: { objArg: boolean } = undefined
) => {}
If you want to make an parameter optional, you should use ?(question mark) before :如果要使参数成为可选参数,则应在 ?(问号)之前使用:
and optional parameter has to be the last parameter of function.可选参数必须是函数的最后一个参数。 For more information check this page.
有关更多信息,请查看此页面。 https://www.typescripttutorial.net/typescript-tutorial/typescript-optional-parameters/
https://www.typescripttutorial.net/typescript-tutorial/typescript-optional-parameters/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.