Nullable Types / Non Nullable Types in TypeScript

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.

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.

Now, open the tsconfig.json and add the strictNullCheck: true as shown below

Now, if you look at the code, you will see the compiler error.

In strict null checking mode, we can assign the null and undefinedonly 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

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.

You can use union types in function argument, function returns types etc.

References

Typescript 2.0

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top