What if I truly require the option for the elapsedTime to be optional?
If it is truly necessary, then go ahead and make it optional (using the ?
). However, there is a high probability that you actually do not need it. It is more likely that you may be misinterpreting its impact. By making it optional, it becomes unpredictable what will be passed into the callback function. Here's an example:
const doRandomStuff = (callback: (elapsedTime?: number) => void) => {
const before = Date.now();
// perform tasks that take time
if (Math.random() > 0.5) {
callback(Date.now() - before);
} else {
callback();
}
}
doRandomStuff((elapsed?: number) => {
if (typeof elapsed === 'number') {
console.log('elapsed', elapsed);
} else {
console.log('no elapsed time was provided');
}
});
It is more probable that what you really want is "you can choose to use the elapsed time or not". However, this can already be achieved with mandatory arguments, so there is no necessity to make any changes. For example:
const doPredictableStuff = (callback: (elapsedTime: number) => void) => {
const before = Date.now();
// perform tasks that take time
callback(Date.now() - before);
};
// This is acceptable
doPredictableStuff((elapsed) => {
console.log('elapsed', elapsed);
});
// And this is also valid
doPredictableStuff(() => {
console.log('task completed');
});