Reputation: 113
I was reading the do's and don'ts section of the Typescript documentation and there's a don't about passing optional paramaters to a callback function. Here's the example:
/* WRONG */
interface Fetcher {
getObject(done: (data: any, elapsedTime?: number) => void): void;
}
But I'm wondering what if I really do need the elapsedTime to be optional, how I would go about doing it if not by making it explicitly optional with the ? decorator?
Upvotes: 1
Views: 1258
Reputation: 85102
what if I really do need the elapsedTime to be optional,
If you really need it, then do it (using the ?
). But you very likely don't need it. Rather, it's more likely that you misunderstand what effect it will have. Making it optional means it's unpredictable what will be passed into the callback. For example:
const doRandomStuff = (callback: (elapsedTime?: number) => void) => {
const before = Date.now();
// do some stuff that takes 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 received');
}
});
More likely, what you're after is "you can use the elapsed time if you want, or not use it". But that's already the case with mandatory arguments, so you don't need to do anything to achieve that. For example:
const doPredictableStuff = (callback: (elapsedTime: number) => void) => {
const before = Date.now();
// do some stuff that takes time
callback(Date.now() - before);
};
// This is legal
doPredictableStuff((elapsed) => {
console.log('elapsed', elapsed);
});
// And so is this
doPredictableStuff(() => {
console.log('done');
});
Upvotes: 4