[Typescript 2] Nullable Types - Avoiding null and undefined Bugs

For example you have a TS app:

enum PaylerPosition {
    Guard,
    Forward,
    Center
}

interface Player {
    name: string;
    position: PlayerPosition;
}

let kobe = {
    name: 'Kobe',
    position: PlayerPosition.Guard
};

The problem for this piece of code is that, you can assign 'kobe' to null, or undefined. And compiler won't catch this error by defualt.

 

In TypeScritp 2, it includes a new rule:

"strictNullChecks": true

We can set this in tsconfig.json file.

Then it will catch if variable are assigned to 'null' or 'undefined'.

posted @ 2017-03-06 17:16  Zhentiw  阅读(252)  评论(0编辑  收藏  举报