TypeScript Reference ยท Keywords and Declarations
The void operator and the void type
Reference for void in TypeScript: the return type of functions that return nothing, the callback rule, void versus undefined, and the void operator.
void appears in two roles. As a type, it marks a function that does not produce a useful result. As a JavaScript operator, void expression evaluates the expression and always returns undefined.
The type is the common one: function log(m: string): void says callers should not use the return value. It is close to, but not the same as, undefined: a function whose type returns void may return anything when it is used as a callback, while a function declared to return undefined must return it.
function log(message: string): void { console.log(message); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
function f(): void {} type Callback = () => void; let v: void = undefined; void expression
| Form | Description |
|---|---|
: void on a function |
The function returns no useful value. With an explicit annotation, a return with a value is an error. |
() => void as a type |
Any function can be assigned, whatever it returns. The result must not be used. |
void expr |
Evaluates expr, discards it, gives undefined. |
Edge cases and errors:
- Only
undefined(andany,never) is assignable to a variable of typevoid; withstrictNullChecks,nullis not. - A function expression with a
voidreturn type annotation cannot return a value; an arrow function assigned to avoid-returning function type can. - A
voidresult cannot be tested for truth meaningfully:if (f())wherefreturnsvoidis error TS1345. Promise<void>is a promise that resolves with no value;awaitgivesundefined.voidandundefineddiffer in generics: a parameter of typevoidcan be omitted, soresolve()works forPromise<void>.
Usage notes
- Prefer
voidas a return type when the function is used for side effects. Useundefinedwhen callers need the valueundefinedexplicitly. - Do not use
voidas a parameter or property type except for generics, where it means "nothing to pass". - The operator form is mostly used as
void promiseto mark an intentional fire-and-forget call (linters flag unhandled promises), and asvoid 0in older code for a safeundefined. voidis unrelated tonever:nevermeans the function does not return at all (it throws or loops).- A method declared
(): voidin an interface can be implemented by a method that returns something, which is why the callback rule exists.