HomeContact
Typescript
Difference between void and never in Typescript.
March 29, 2021
1 min

When we declare a function in Typescript, if the function return nothing we can use any, void or never. any should be used when you don’t know exactly what to use between void or never. In this article we will define use case for void and never in Typescript. Click here if you just want to see how to declare function in Typescript

Void

The void type is like having no type at all. A function that returns nothing in Typescript/Javascript actually return undefined.

const test = (arg): void => {
  console.log(arg)
}

console.log(test('test'))

// "test"
// undefined

Here void is useful to show that we expect nothing in return of this function, and that undefined is not an error

Never

The never type in Typescript is useful fore defining a function that never returns. It must always have an unreachable endpoint. For example, a function that has an infinite loop will never return something :

const renderGame = (game: Game): never => {
  while (true) {
    game.renderFrame()
  }
}

Another type of function that can be used with never can be a Typescript function that always throw an error :

const throwError = (message: string): never => {
  throw new Error(message)
}

throwError('Error occurred')

Conclusion

  • never : for typescript function that will never return something, can be always running or throw some error (doesn’t have time to return).
  • void: for Typescript function that will return nothing.
  • any: for Typescript function where you are not sure of it returns.

For better knowledge with Typescript, check how to declare functions in Typescript interface


Tags

javascripttypescript

Related Posts

How to declare functions in Typescript interface.
March 25, 2021
1 min
© 2022, All Rights Reserved.

Quick Links

Contact Us

Social Media