Tuesday 15 January 2019

Nullable References

Reading about the new features that C# will delight us with I felt a bit surprised with the Nullable References one. If you enable the feature, references will be considered as not nullable, unless that you explicitely state the contrary by defining it like this: MyType? mt;. Trying to assign a null value to a reference not declared as nullable will cause the compiler to throw a warning. There are no runtime verifications, it's all at compile time, and it won't prevent your code from being compiled, as I say it will just throw a warning. This warning should be enough to make you review your code and save you many potential problems at runtime.

I pretty much liked the feature and it seemed like something totally new to me, but indeed something almost identical exists in TypeScript since version 2.0. Non-nullable types can be enabled with the --strictNullChecks compiler option. Using this feature will make the compiler throw an error (but well, it's TypeScript, so the code will still get transpiled into JavaScript) each time you try to assing a "null like value"m that is, null or undefined. If when using the feature you want one reference to accept any of those values you'll have to define it like this:

let y: number | undefined;
let z: number | null | undefined;

Notice that this TypeScript feature has nothing to do with the ? optional properties that you can define in types and that so nicely play with the TypeScript structural typing nature.

No comments:

Post a Comment