Why is never assignable to every type?

后端 未结 3 1545
天涯浪人
天涯浪人 2021-01-13 16:02

The TypeScript documentation says that

The never type is a subtype of, and assignable to, every type

but doesn\'t m

3条回答
  •  有刺的猬
    2021-01-13 16:45

    How type-checking works for assignments?

    Take the R-value (right side of assignment). Verify if it can assume a value which the L-value (left side of assignment) can not. If any such value exists, then reject the assignment. Otherwise, it's fine.

    Let's see examples:

    let x: number;
    let y: never;
    
    x = y; // OKAY, can assign any given `never` value to a number
    
    y = x; // Not OKAY, x can be, among other values, 1, which is can not be assigned to never
    

    It looks absurb, as an assignment needs to move some data into the designated storage for a given variable, and no value exists, since it's not a runtime type. In practice though, an assignment from never to any other type, while valid, won't actually run (except if you trick TypeScript with type assertions).

    Does that make sense?

提交回复
热议问题