What is the difference between never and void in typescript?

前端 未结 8 2382
刺人心
刺人心 2020-12-15 15:04

I have read this, but it is unclear what would be the difference between \'never\' and \'void\' type?

8条回答
  •  醉酒成梦
    2020-12-15 15:36

    Never is information that this particular part shouldn't be reachable. For example in this code,

    function do(): never {
        while (true) {}
    }
    

    you have an infinite loop and we don't want to iterate infinite loop. Simply as that.

    But a real question is how can it be useful for us? It might be helpful for instance while creating more advanced types to point what they are not

    for example, let's declare our own NonNullable type:

    type NonNullable = T extends null | undefined ? never : T;
    

    Here we are checking if T is null or undefined. If it is then we are pointing that it should never happen. Then while using this type:

    let value: NonNullable;
    value = "Test";
    value = null; // error
    

    Void is information that functions with this type don't return any value, but they are reachable and they can be used.

提交回复
热议问题