Why is never assignable to every type?

后端 未结 3 1543
天涯浪人
天涯浪人 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 17:07

    You are not calling the useNever function. If you try to call it with a parameter it will fail since a value can not be never. But as always, you can trick the compiler with typeguards e.g. this will work

    const test = (val: string | number) => {
         if (typeof val === "string") {
    
         } else if (typeof val === "number") {
    
         } else {
             useNever(val); // works, since val is not number or string it is implicitly never
         }
     }
    

提交回复
热议问题