Return Types of Callbacks

Return Types of Callbacks

Don’t use the return type any for callbacks whose value will be ignored:

/* WRONG */
function fn(x: () => any) {
  x();
}

Do use the return type void for callbacks whose value will be ignored:

/* OK */
function fn(x: () => void) {
  x();
}

Why: Using void is safer because it prevents you from accidently using the return value of x in an unchecked way:

function fn(x: () => void) {
  var k = x(); // oops! meant to do something else
  k.doSomething(); // error, but would be OK if the return type had been 'any'
}
doc_TypeScript
2016-10-04 19:25:33
Comments
Leave a Comment

Please login to continue.