The never type, as Typescript’s primitive type, has long been a mystery because it is rarely used in real-world situations. It describes values that will never appear. I closed my eyes and thought: if a value is something I can never get to or appear at, why don’t I delete it? The compiler immediately replied: you are so arrogant, why don’t you compile your own code!

The never type generally has two usage scenarios:

  • As the return value of a function, describing functions that cannot be returned

  • Under type protection, describes a type value that is never true

Don’t ask questions. I know it’s not human. Let’s take a practical example.

A function that can never return

A function that will never return. I close my eyes and think: Hehe, what fool can write such code? The compiler immediately replied, “You idiot!”

Scenario 1: An infinite loop

const func = function() :never{
  while(true) {console.log('You big fool! ')}}Copy the code

You want to fly?

Scenario 2: Throwing an exception

const func = function() :never{
  throw new Error('Wake up')}Copy the code

Don’t hide your ignorance with a line of console

Type protected to logical dead zone

Intelligence is a good thing. If you have to compare yourself to a computer in logic, compare yourself to a computer.

Scenario: Variable types that cannot be inferred

const handleStringOrNumber = function(value:string|number){
  if(typeof value === 'string') {/ / I am a string
  }else if(typeof value === 'number') {/ / I am a number
  }else{
    // Who am I? Where I am
    // Value is of type never}}Copy the code

There is nothing wrong with being precise

Soul Torture: Never as a primitive type in relation to other types?

I asked you to see the file. Did you see it? What if you don’t look at me? I can only copy it for you:

  • The never type is a subtype of all types and can be assigned to any type of value

  • No type other than never is a subtype of never, nor can it be assigned to a variable of never

  • In a function expression or arrow function, if the function does not declare a return type and there is no return statement whose return cannot reach the bottom of the function, the return type of the function is inferred to be never

  • If a function has an explicit return type declaration of type never, all return statements within the function must either explicitly return type never, or the function bottom can never be reached

We’ll talk about the weird behavior of the never type in functions next time.