[Typescript 2] Nullable Types

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'.

原文地址:https://www.cnblogs.com/Answer1215/p/6510926.html