1

I would like to know the difference between these four types in TypeScript and some practical examples of how to use them. Please don't mark my question as a duplicate of this, as I'm talking about TypeScript types at compile time and not Javascript values.

Gerard
  • 23
  • 5

1 Answers1

1
  1. undefined means that variable haven't been defined
function foo(bar?: number) {
  console.log(bar) // prints undefined
}

The undefined type is a primitive type that has only one value undefined.

  1. The null value represents the intentional absence of any object value.

The value null is written with a literal: null. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

  1. void is very similar to undefined. It is also type that contains single undefined value. But it has special meaning in function return types. And works a little bit different in type compatibility

The intent of void is that a function's return value will not be observed. This is very different from will be undefined

  1. never means that a function with this return type can never return normally at all. This means either throwing an exception or failing to terminate. never is type contains no values
Evgeny K
  • 1,744
  • 3
  • 13
  • 19