Thursday, June 9, 2022

Angular making input variable Optional

function example(x: number?, y?: string) {

 // …

}

“?” Suffix

The first one indicates a nullable parameter that can also be a number, undefined or null. But, the second argument is an optional, it can be a string or undefined.

Undefined vs Null

Again here some may not be aware of the difference between “undefined” and “null”. Undefined represents something that may not exist. Null is used for things that are nullable. So both are entirely different.

@Optional? As the official document says, Optional is a constructor parameter decorator that marks a dependency as optional. This clearly states that @Optional is used in the context of DI (Dependency Injection). 

@Injectable()

class Car {

    constructor(@Optional() public engine: Engine) {}

}

When @Optional is used, no exceptions occur even when the injected dependency is undefined. It treats the dependency as optional. Same thing happens if we replace @Optional annotation with “?”. The injector search for the dependency and when it is undefined, it will throw the exception.

Eventhough sometimes replacing these doesn’t make any difference in the way your code executes, it is necessary to understand that always good to follow best practices and the recommended ways as a good developer.

references:

https://medium.com/@angela.amarapala/understanding-the-usage-of-optional-and-nullable-in-typescript-826c1754df3




No comments:

Post a Comment