Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a type to all optional named parameters

I am trying to write all optional named parameters for a TypeScript function.

But I am having a lot of trouble assigning a type to the parameters, as can be illustrated by this example:

type Params = {
    foo: {
        bar: string,
        baz?: string
    }[]
}

function testFunction({foo= [{bar: "hi", baz: "there"}, {bar: "hello"}]}={}: Params) { // This fails, I don't know how to type it here
    console.log(foo)
}

testFunction()

What’s the correct way to use named optional parameters in TypeScript while also being able to type the optional parameter object?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading