顾名思义,主要是排除变量中 nullundefined 的类型。

    1. interface Item {
    2. parent: Item | null;
    3. }
    4. const fn = (item: Item) => {
    5. if (!item.parent) {
    6. return;
    7. }
    8. const _fn = () => {
    9. const p1 = item.parent.parent; // error: (item.parent)对象可能为 null
    10. const p2 = (<Item>item.parent).parent // ok,item.parent 整体断言
    11. const p3 =item.parent!.parent; // ok,item.parent 非空,则排除 null
    12. }
    13. }