TypeScript 2.0 beta non-nullable types

by DotNetNerd 13. July 2016 07:19

tsOne of the nice features of functional programming languages like F# is the lack of null. Not having to check for null every where makes code a lot less errorprone. As the saying goes "What can C# do that F# cannot?" NullReferenceException". Tony Hoare who introduced null references in ALGOL even calls it his billion-dollar mistake. The thing is that although this is quite a known problem, it is not trivial to introduce non nullable types into an existing language, as Anders Hejlsberg talked about when I interviewed him at GOTO back in 2012.

With version 2.0 of TypeScript we do get non-nullable types, which has been implemented as a compiler switch --strictNullChecks. If the switch is turned on the following will cause an error.

let something: string = null;

There might be cases where you still want something to be null if you are explicit about it. This is possible with the null and undefined types, that can be used in union types like this.

let something: string | null = null;

In cases where you know that a type is not null, but it cannot be verified by the type system, it is possible to use the ! postfix operator to tell the compiler that this is the case.

declare let names: string[] | undefined;
let shoutedNames = names!.map(s => s.toUpperCase());

It is a feature I have been looking forward to for a while, and now it is finally available in the current beta.

Who am I?

My name is Christian Holm Diget, and I work as an independent consultant, in Denmark, where I write code, give advice on architecture and help with training. On the side I get to do a bit of speaking and help with miscellaneous community events.

Some of my primary focus areas are code quality, programming languages and using new technologies to provide value.

Microsoft Certified Professional Developer

Microsoft Most Valuable Professional

Month List

bedava tv izle