# TypeScript `never` type ## Some function `never` return ```ts= // example1: const willFail = () => { throw new Error('not implemented'); }; // example2: const forever = () => { while (true) { // do something } }; // example3: const foo = 123; if(foo !== 123) { let bar = foo; // bar is 'never' bar = 456; // Type 'number' is not assignable to type 'never'. } ``` ## `never` is convenient to do exhaust checks in union types ### Use `switch` to discriminate union ```ts= interface Foo { type: 'foo' } interface Bar { type: 'bar' } type All = Foo | Bar function handleValue(val: All) { switch (val.type) { case 'foo': // val is Foo here break case 'bar': // val is Bar here break default: // val is 'never' here const exhaustiveCheck: never = val break } } ``` ### Use `if` to discriminate union ```ts= function foo(x: string | number): boolean { if (typeof x === 'string') { return true; } else if (typeof x === 'number') { return false; } // If it is not `never` type, it would show an error. return fail('Unexhaustive'); } function fail(message: string): never { throw new Error(message); } ```