Never say never!

In many programming language we have some basic types: strings, numbers, objects and so on. But a few weeks ago I met type never in typesctipt. So… a couple words about it.

Never is a very specific but also very useful type. We can add typing to the variable, which:

  • never will be using

… wait, what? On the first look it make no sense. But please look at the examples below:

function error(message: string): never {
    throw new Error(message);

Function returning Error must be type never (is unreachable).

type Shape = Circle | Square;
interface Circle {
interface Square {
function getArea(shape: Shape) {
 switch(shape.type) {
  case”circle”: {
  return Math.PI *shape.radius*shape.radius;
 case”square”: {
  return shape.width*shape.width;
 default: {
  let shouldNeverBe:never=shape;
Hier, in default, varaible shouldNeverBe never be use. But look closer. If you have big project with many files and 5 months later you will have to add a new interface (Triangle) how this type never in default protects you from push your change (type Shape + new interface) to the production?
Of course it throws new Error. And next you will add new case to your switch.
More information about never in typescript:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s