Optional Parameters in Callbacks

Optional Parameters in Callbacks

Don’t use optional parameters in callbacks unless you really mean it:

/* WRONG */
interface Fetcher {
  getObject(done: (data: any, elapsedTime?: number) => void): void;
}

This has a very specific meaning: the done callback might be invoked with 1 argument or might be invoked with 2 arguments. The author probably intended to say that the callback might not care about the elapsedTime parameter, but there’s no need to make the parameter optional to accomplish this – it’s always legal to provide a callback that accepts fewer arguments.

Do write callback parameters as non-optional:

/* OK */
interface Fetcher {
  getObject(done: (data: any, elapsedTime: number) => void): void;
}
doc_TypeScript
2016-10-04 19:25:28
Comments
Leave a Comment

Please login to continue.