liveBook · Manning

Optional function argument

As explained in Pro Angular 16

An optional parameter is a function parameter that may be omitted when the function is called.

Mark a parameter with `?` to let callers omit its argument. When omitted, its value is `undefined`; within the function, its type includes `undefined`. This differs from a required parameter typed `string | undefined`, which still requires an argument. section 4.2.1

Listing 4.3. Defining an optional parameter in the main.ts file in the src folder
function writeValue(val?: string) {
    console.log(`Value: ${val ?? "Fallback value"}`)
}

writeValue("London");
writeValue();

A string parameter can be omitted, and nullish coalescing supplies a fallback for the resulting `undefined` value. section 4.2.1

Optional constructor parameters also let a `Product` be created without supplying every model property, which can help when HTML forms populate the object. section 5.3.1

Listing 5.11. The contents of the product.model.ts file in the src/app/model folder
export class Product {
 
    constructor(
        public id?: number,
        public name?: string,
        public category?: string,
        public description?: string,
        public price?: number) { }
}

The Product constructor marks each model property as optional, allowing object creation with omitted values. section 5.3.1

How Pro Angular 16 covers it

How deep it goes
Defines the `?` syntax, omitted-value behavior, inferred `undefined`, and distinction from a required `string | undefined` parameter.
Examples
Uses a string-printing function with a fallback and Product constructors with omitted model fields.
What you can do after
Apply optional parameters to let calls omit arguments or create partially populated Product objects.
How it connects
Connects optional parameters with TypeScript parameter types, union types, constructors, and form-populated model properties.

Also explained in

Compare how 4 books explain optional function argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.