Typescript types are Nullable Types. i.e you can assign Null
& undefined
to any of the types. The compiler will not throw any error. But from the Typescript version 2.0, we can define Non Nullable types with the --strictNullChecks
flag on. The strictNullChecks
is flag is set to false
by default. But, when set to true
in tsconfig.json
it stops us from assigning the null
& undefined
to a type. Thus converting the types into Non Nullable types.
Table of Contents
StrictNullChecks
In the following example, we have an interface Employee
with two properties. employeecode
& name
. As you can see from the example, Typescript allows us to assign null
or undefined
to the name
property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | interface Employee { employeecode: number name:string } let e1:Employee = { employeecode:10, name:null } let e2:Employee = { employeecode:10, name:undefined } let e3:Employee=null; |
Now, open the tsconfig.json
and add the strictNullCheck: true
as shown below
1 2 3 4 5 6 7 8 9 | { "compilerOptions": { "strictNullChecks":true } } |
Now, if you look at the code, you will see the compiler error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | interface Employee { employeecode: number name:string } let e1:Employee = { employeecode:10, name:null //Type 'null' is not assignable to type 'string'.ts(2322) } let e2:Employee = { employeecode:10, name:undefined //Type 'undefined' is not assignable to type 'string'.ts(2322) } let e3:Employee=null; //Type 'null' is not assignable to type 'Employee' |
In strict null checking mode, we can assign the null
and undefined
only to themselves and any
type.
Making Types Nullable
Using Unions
In strict null checking mode, we can still make the Types Nullable by using the Union Types as shown in following examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | interface Employee { employeecode: number name:string|null|undefined } let e1:Employee = { employeecode:10, name:null } let e2:Employee = { employeecode:10, name:undefined } let e3:Employee|null|undefined = null; |
1 2 3 4 5 6 | let name: string | null | undefined; name = "Rahul"; // OK name = null; // OK name = undefined; // OK |
Marking Property & Parameter Optional
Another way to allow undefined
is by making the Property or Parameter optional by using the ?
after the property/parameter name. This only allows undefined
, and does not allow null
. i.e because ?
internally creates the union type between the type that we declared and the undefined
type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | interface Employee { employeecode: number name?:string } let e2:Employee = { employeecode:10, name:undefined //ok } let e1:Employee = { employeecode:10, name:null //Type 'null' is not assignable to type 'string | undefined'.ts(2322) } |
You can use union types in function argument, function returns types etc.
1 2 3 4 5 6 7 8 | function getLength(s: string | null) { if (s === null) { return 0; } return s.length; } |