TypeScript is indifferent
When using setCallback()
, all you need to provide is a reference to a function, which can be of any type. As long as the function itself is not invoked, TypeScript considers it an object
. This means that TypeScript will not throw a TypeError as long as your function expects an object
.
If the object
is called, TypeScript will identify any mismatches and provide a TypeError accordingly.
- Passing by reference
In Pass by Reference, a function receives the reference or address of a variable as its argument. Modifying the argument within the function impacts the original variable passed from outside the function. In JavaScript, objects and arrays are examples of entities passed by reference.
- Understanding Functions (MDN)
A function serves as a "subprogram" callable by external code or even internally in the case of recursion. Similar to a program, a function consists of statements forming the function body. Data can be sent to a function for processing, with the function returning a value upon completion.
Functions in JavaScript are treated as first-class objects, possessing properties and methods akin to regular objects. However, what sets them apart is their invocable nature; functions can be executed like Function objects to perform specific tasks.
Illustration: Example 1
Due to limitations regarding void functions and the impossibility of utilizing .then()
, I had to resort to creating an IIFE to enable async
functionality. Surprisingly, this approach functions properly despite anticipating a callback of void type.
const setCallback = (cb: () => void): void => {
(async () => await cb())().then(() => console.log("Hi"));
};
const callback = (): Promise<number> => {
return new Promise(resolve => {
setTimeout(() => resolve(0), 100);
});
}
setCallback(callback);
Exploring Further: Example 2
If an attempt is made to execute the function with a return type of Promise
:
The 'Promise' argument does not align with the expected '() => void' parameter.
The 'Promise' type lacks compatibility with the signature '(): void'.
This error highlights the discrepancy in Function signatures.
const setCallback = (cb: () => void): void => {
(async () => await cb())().then(() => console.log("Hi"));
};
const callback = (): Promise<number> => {
return new Promise(resolve => {
setTimeout(() => resolve(0), 100);
});
}
setCallback(callback());