Understanding Nullable Types in Typescript with examples
Understanding Nullable Types in Typescript with examples:
Nullable type is introduced in typescript 2.0, this helps us to keep initialized objects to have some values other than null all the time.
Default number | Assigning null:
let home2OfficeKm = 10;
home2OfficeKm = null;
Works fine in typescript 2.0 earlier versions, if you do not want null to be assigned to the home2OfficeKm anytime then you can add the below entry in your tsconfig.json file
// add this with your existing compilerOptions properties in the tsconfig.json file
then the above snippet throws the “Type null is not assignable to type number” error.
But same thing won’t happen to the below snippet,
Default undefined | Assigning null:
home2BeachKm = null;
This is because the above snippet is not initialized with any default values like the one(number=10) we saw above, so it accepts null for home2BeachKm variable.
Thing you have many variables and if you enable
strictNullChecks then it works for all the variable same way, then the variable which can be assigned up with null also could create the issue,
In those timings you can actually use,
Default union(null | number) | assigned with null:
let km: null | number =18;
km = null;
Then this also wont create any issue, because km is of union types with null and number. So it will allow both numbers and null.
Default null | assigned with number:
let home2OfficeKm = null;
home2OfficeKm = 10;
This also throws the error.
Nullable Types – Things to keep in mind:
- Introduced in typescript 2.0 only
- “strictNullChecks”:true should be enabled in the tsconfig.json to make use of this feature/type.
- Variables which needs to work with nullable type should be initialized with some variable values like number/string etc. Then only it will not allow the null to get assigned for the variables which is assigned with the default values.
- It will not work for the variables which is only declared and does not assigned with default values. So it will be assigned with undefined by default and this nullable type will not work with undefined value variables.
110 total views, 2 views today