There is no such thing as "named parameters" in TypeScript or JavaScript. What you have is an optional parameter which is an object. And the syntax is the same as always: name: Type = defaultValue
. The name
can immediately be unpacked as {foo}
; the Type
is Params
and the defaultValue
is the default value of the entire object. So this is the correct syntax:
function testFunction({foo}: Params = {foo: [{bar: "hi", baz: "there"}, {bar: "hello"}]}) {
console.log(foo)
}
But the default value won't help you here, because you said you wanted to emulate all optional named parameters. If you pass an object, the default value is entirely ignored, so the above is an all-or-nothing approach.
Instead, you'll have to make the default of each field in the object be undefined
:
type Params = {
foo?: {
bar: string,
baz?: string
}[],
qux?: number,
}
Then assign the default inside the function:
function testFunction({foo, qux}: Params = {}) {
// Assign default values if a parameter is undefined
foo = foo !== undefined ? foo : [{bar: "hi", baz: "there"}, {bar: "hello"}]
qux = qux !== undefined ? qux : 42
}
You can still set {}
as the default if the argument is entirely omitted, which will then do the same as omitting all object keys.
See e.g. this question for some more examples.