TypeScript: Typecheck passes for incorrect assignment

Hello,

This code typechecks fine: const some : ((arg : string) => boolean) = () => true

In the same time it looks obviously incorrect. Since the “arg” in the type definition is not optional. So the function w/o argument is assigned to the variable, which has a type of function with 1 argument.

I’d understand if this would typechecks (it does) const some1 : ((arg? : string) => boolean) = () => true but not the above.

I’ve tried running it with --strictFunctionTypes and it typechecks as well.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 22 (11 by maintainers)

Most upvoted comments

Following your logic, why not make the const some : string = 11 valid?

Because (11).toUpperCase() crashes but (() => null)("foo") doesn’t. And code like the latter is running all the time in JavaScript programs (via indirection) to no ill effect.

If I declare const some : ((arg? : string) => boolean) then it can be function with 1 or 0 arguments.

You say you want to disallow unsafe assignments. In your world, this code is legal:

// Callee may have zero or one arguments
const some: ((arg?: string) => string) = arg => arg.toUpperCase();
// When invoking a function, you don't need to provide optional arguments (by definition)
some();

and it crashes. What’s “safe” about this? How do you imagine changing the definition of “optional” in this world?