TypeScript Void

Understanding TypeScript Void Type: A Comprehensive Guide with Examples

TypeScript is a statically typed superset of JavaScript that includes additional features like interfaces, classes, and types. One of these types is the “void” type, which represents the absence of a value. In other words, a function that returns void does not return any value. In this lesson, we will explore the “void” type in TypeScript and provide examples of how it can be used.

Defining a Function that Returns Void To define a function that returns void in TypeScript, we simply specify the return type as void. Here is an example:

function logMessage(message: string): void {
    console.log(message);
}

In this example, the function “logMessage” takes a string parameter and logs it to the console. The return type is specified as void, indicating that the function does not return a value.

Using the Void Type with Callbacks The “void” type is commonly used with callbacks, which are functions that are passed as arguments to other functions. Callback functions typically do not return a value, so they are often specified with a return type of void. Here is an example:

function doSomethingAsync(callback: () => void): void {
    setTimeout(() => {
        // do something asynchronous
        callback();
    }, 1000);
}

doSomethingAsync(() => {
    console.log("Async operation complete!");
});

In this example, the function “doSomethingAsync” takes a callback function as an argument. The callback function is specified with a return type of void, indicating that it does not return a value. The callback function is executed after the asynchronous operation completes.

Using the Void Type with Classes The “void” type is also commonly used with methods in classes. Methods that do not return a value are specified with a return type of void. Here is an example:

class MyClass {
    private _value: number;

    constructor(value: number) {
        this._value = value;
    }

    setValue(newValue: number): void {
        this._value = newValue;
    }
}

const myObj = new MyClass(10);
myObj.setValue(20);

In this example, the class “MyClass” has a method called “setValue” that sets the value of a private property called “_value”. The method is specified with a return type of void, indicating that it does not return a value. The method is called on an instance of the class, “myObj”, which sets the value to 20.

Conclusion

The “void” type in TypeScript is used to indicate that a function or method does not return a value. It is commonly used with callbacks and methods in classes. By understanding how to use the “void” type effectively, you can write safer and more robust TypeScript code.