Now, we will explore TypeScript’s void return type through two interfaces, ITest1 and ITest2. We’ll examine how it defines functions that don’t return a value and explore potential pitfalls, such as scope issues.
Example
interface ITest1 {
log(): void;
}
interface ITest2 {
log: () => void;
}
const test1: ITest1 = {
log() {
console.log("Test1 works", this);
},
};
test1.log();
const test2: ITest2 = {
log: () => {
console.log("Test2 works", this);
},
};
test2.log();
The ITest1
interface, uses the traditional method declaration syntax for defining methods, whereas the second interface, ITest2
, uses an arrow function syntax to define the method.
Both interfaces declare a method named log
that takes no arguments and returns void, they differ in syntax, function type, and the way they handle this context.
The log
method from ITest1
can access the object’s properties using this
. The log
method from ITest2
can’t access the object’s properties using this
. The ITest2
interface captures the this
value from the surrounding lexical scope where it is defined, not from where it is called.
Arrow functions (() => { … }
) behave differently from regular functions when it comes to the this
keyword. Arrow functions do not have their own this
context. Instead, they inherit the this
value from the surrounding lexical scope, such as the global object. This means that within an arrow function, this
retains the value of this
from the enclosing context where the arrow function is defined, regardless of how or where the function is called.