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.
Asked
Active
Viewed 117 times
1
-
first question is about JS values, not TS types, so I am not sure that it is duplicate – Evgeny K Dec 27 '22 at 18:00
-
I agree, I tried to search for this specific question before posting and there are no similar ones. – Gerard Dec 27 '22 at 22:42
1 Answers
1
undefinedmeans 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.
- The
nullvalue 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.
voidis very similar toundefined. It is also type that contains singleundefinedvalue. 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
nevermeans that a function with this return type can never return normally at all. This means either throwing an exception or failing to terminate.neveris type contains no values
Evgeny K
- 1,744
- 3
- 13
- 19