Angular is being widely used by developers as a front-end web application development platform. As an open-source platform, Angular is built with TypeScript, a superset of JavaScript. It is good for Angular developers to have an understanding of how things happen with TypeScript. So, in this article, let us discuss about some of the differences between nullable and optional parameters.
Common misconception
Most developers fall into the category of misunderstanding nullable and optional parameters. The confusion arises on where to use the “ ? ”. Look at this code block.
function example(x: number?, y?: string) {
// …
}
“?” Suffix
Notice carefully where the “?” is suffixed. In the first argument it is suffixed to the type of the parameter whereas in the second, it is suffixed to the name of the argument. Do you think both are same?
The answer is no. 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.
x // =\> number | undefined | null
y // =\> number | 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]
So what is this @Optional in angular is all about? What is the difference between “?” and @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). Here is an example from the official docs.
@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 will search for the dependency and when it is undefined, it will throw the exception.
It is always nice to follow the best practices and learn something new :)
Top comments (0)