I have read this, but it is unclear what would be the difference between 'never' and 'void' type?
10 Answers
As Marius Schulz discusses in this article,
- A function that doesn't explicitly return a value implicitly returns the value
undefined
in JavaScript. Although we typically say that such a function "doesn't return anything", it returns. We usually ignore the return value in these cases. Such a function is inferred to have avoid
return type in TypeScript.- A function that has a
never
return type never returns. It doesn't returnundefined
, either. The function doesn't have a normal completion, which means it throws an error or never finishes running at all.
-
9
-
1
In imperative languages, void
can be thought of as a type containing a single value. Such languages do not provide a means to construct or consume this value, but a void
function can be thought of as returning this trivial value.
In contrast never
is a type containing no values, which means that a function with this return type can never return normally at all. This means either throwing an exception or failing to terminate.
-
10Incorrect for
void
in most imperative languages. In those languages,void
is the bottom type, which has no value exactly (e.g. a function argument can't be ofvoid
type). The answer confuses bottom type with unit type.– FrankHBApr 7, 2018 at 2:46 -
3@FrankHB - If that were true then functions with a
void
return type would never return at all, which is not necessarily the case. Calling avoid
function is a statement in these languages, and statements are mapped to expressions of typeunit
in expression-oriented languages like Rust, F# etc.– LeeApr 7, 2018 at 8:17 -
This is still false for those cases in C, C++, Java... Technically, statement is usually strictly distinct with expression (e.g. expression has no trailing ';' in those C-ish languages), and few languages allow expressions being reduced to statements. A statement formed by a function call expression is an "expression statement", which is forbidden to be a function argument syntactically. OTOH a function call expression can be syntactically correct argument, but disallowed by typechecking against
void
. It has nothing to do with termination property yet.– FrankHBApr 10, 2018 at 3:13 -
2Well, I'd reconstruct my words. The objection is to your first statement. As you have said, "in imperative languages", where the imperative languages should be the object languages (like Typescript here). Your statement suggests the
void
type is allowed by rules of them as a real unit type, which is not the fact (e.g. in the case I gave). Moreover, treatingvoid
as a unit type does not make help at all (if not confusing), as long as you ignore how the implementations actually utilize the type.– FrankHBApr 11, 2018 at 2:29 -
2Most of such languages (at least C-ish ones) has
void
as one of the static type, handled by the typechecker as mandatory. The violation shall be detected by typechecking on the ill-typed expressions. This has nothing to do with termination of called functions in object languages, even if it does make the translation (including typechecking) not terminate normally. The translation should terminate though, due to additional requirements of diagnostics rules. Replacingvoid
with a unit type in the translation to make it always terminate is an implementation detail.– FrankHBApr 11, 2018 at 2:30
To augment Lee's very good answer, another way to think of it is that in a correctly-typed program, a never
value cannot be observed.
In addition to functions which never return (or which always throw exceptions), you'll see the never
type when a union type has been exhausted of all its possible constituents:
// Example assumes --strictNullChecks
function fn(x: number | string) {
if (typeof x === 'number') {
// x: number in this block
} else if (typeof x === 'string') {
// x: string in this block
} else {
// x: never in this block
// this block does not run; the value of x cannot be observed
}
}
-
2"never value cannot be observed": I thought it is the same for 'void' value, no?– ironicApr 4, 2018 at 18:58
-
1@ironic In theory they are distinct things.
void
is unit type, it has only one (quite useless) value. On the other handnever
is bottom type. It has no value. The usefulness of this distinction between two seemingly same things is not always obvious and indeed in many situations one is interchangeable with the other for all practical purposes but a very sharp theoretical distinction does exist. Feb 3, 2019 at 23:56 -
1@ironic I can think of a somewhat intuitive example : a function that is called purely for its side effects and is not supposed to return any value (
print
for example) is of typevoid
. It returns with the only value the typevoid
can hold. You can do absolutely nothing interesting with that value. On the other hand if there is a function that is supposed to never return at all, then the intent is much better reflected by marking it asnever
rather thanvoid
Feb 4, 2019 at 0:03 -
void
isn't a unit type. The return value of a function reference whose return type isvoid
can be anything because it's legal for a non-void
-returning function to be aliased by avoid
-returning type. Feb 4, 2019 at 16:13
In short:
void
returns void
, never
never returns.
-
1You can't really "return void". It means it "doesn't return anything" but because JavaScript is JavaScript, what it actually returns is
undefined
but you shouldn't use that return value for anything, you should pretend like there isn't one.– mpenSep 14, 2022 at 3:21
Also, for more a theorical reason, with --strictNullChecks
new flag, TypeScript needed a new bottom type (since null
and undefined
are no more). The type never
is such a bottom type and make TypeScript's type system more consistent.
Never is information that this particular part shouldn't be reachable. For example in this code,
function do(): never {
while (true) {}
}
you have an infinite loop and we don't want to iterate infinite loop. Simply as that.
But a real question is how can it be useful for us? It might be helpful for instance while creating more advanced types to point what they are not
for example, let's declare our own NonNullable type:
type NonNullable<T> = T extends null | undefined ? never : T;
Here we are checking if T is null or undefined. If it is then we are pointing that it should never happen. Then while using this type:
let value: NonNullable<string>;
value = "Test";
value = null; // error
Void is information that functions with this type don't return any value, but they are reachable and they can be used.
-
Bad example;
let value: NonNullable<string>;
is literally justlet value: string;
– ruoholaAug 21, 2022 at 20:33
The type never means that nothing occurs. It is used when a type guard cannot occur, or in a situation where an exception is always thrown. There is a difference between void and never. A function that has the explicit return type of never won’t allow returning undefined, which is different from a void function which allows returning undefined.
function functionThrow(): never {
throw new Error("This function return never");
}
For example, in the code below, there is an enum with two items. TypeScript knows that only two cases are possible and the default (else) case cannot occur. This insight of TypeScript is perfect since the function return type only accepts string, and does not accept never. If in the future you add a new item from enum, (for example, a ChoiceC without adding a new case in the switch statement), then the code can call the unhandledChoice function which returns never.
enum EnumWithChoices {
ChoiceA,
ChoiceB,
ChoiceC,
}
function functionReturnStringFromEnum(c: EnumWithChoices): string {
switch (c) {
case EnumWithChoices.ChoiceA:
return "A";
case EnumWithChoices.ChoiceB:
return "B";
default:
return unhandledChoiceFromEnum(c);
}
}
function unhandledChoiceFromEnum(x: never): never {
throw new Error("Choice not defined");
}
In the end, never indicates a state not meant to be. An exception is not expected behavior. An infinite loop in a function is not meant to be sustainable in a system, a condition that is never visited should not exist.
The return type of Promise.reject()
is Promise<never>
, meaning "it is never resolved".
So if a function returns Promise<never>
, I think it will return only errors. On the other hand, Promise<void>
might be resolved without value.
-
Seems like this is not the case. See stackoverflow.com/questions/41291341/…– unionalDec 24, 2016 at 19:46
I will add examples. One function that returns nothing just prints to console. Function with side effect.
Correct definitions
function WriteToConsole():void{
console.log('console')
}
function WriteToConsole():any{
console.log('console')
}
Compile error
function WriteToConsole():never{
console.log('console')
}
function WriteToConsole():undefined{
console.log('console')
}
never type usually used when we have throw in the function
-
Having a throw statement in a function does not mean, that the function always returns nothing.– Sebi2020May 15 at 9:41
Here's another difference:
let x: string|never = undefined; // error: Type 'undefined' is not assignable to type 'string'.(2322)
let y: string|void = undefined; // ok