void type
- TypeScript course
- Beginner
- Lesson 28/89
- 4 min
Learn functions that do not return a value with void.
The void type
The void type is the return type of functions that do not return a value. If a function performs an action but produces no result, its return type is void. A void function ends normally, meaning unlike never, the function does finish.
function selam(): void {
console.log("Merhaba");
}void indicates that a function does something but returns no value.
void vs never
The difference between void and never: a void function ends normally but yields no value; a never function never ends. You can write return; in a void function, but return is unreachable in a never function.
function bitir(): void { return; }
function patla(): never { throw new Error(); }void means normal completion; never means no completion.
Practice Write a void function
Define a function named selamVer with an isim parameter of type string and return type void. The function should concatenate "Merhaba, " with isim and print it with console.log. Call the function with "Dünya".
Starter code
// selamVer adında bir void fonksiyon tanımla
// isim parametresini "Merhaba, " ile birleştirip yazdır
// fonksiyonu "Dünya" ile çağırSample solution
function selamVer(isim: string): void {
console.log("Merhaba, " + isim);
}
selamVer("Dünya");Expected output
Merhaba, Dünya
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the <code>void</code> return type indicate?
- The function never completes
- The function returns no value Correct answer
- The function throws an error
- The function returns any type
Explanation: <code>void</code> indicates that the function ends normally but returns no value; <code>never</code> means the function never finishes at all.
2 Add the void return type
function logla(mesaj: string): ____ { console.log(mesaj); }
function logla(mesaj: string): void { console.log(mesaj); }
Explanation: The function performs logging without returning a value; therefore its return type is <code>void</code>. <code>never</code> means the function does not finish, but here it does.
3 void concepts
| Term | Meaning |
|---|---|
void |
Function returning no value |
function f(): void { } |
Completes normally, no value |
void vs never |
void ends normally, never does not |
return; |
Return without a value |