4 ms·
> What language with optional function arguments protects you from this sort of behavior? Languages with a sane type system. TypeScript has no issues catching
by sfvisser 6y ago
> What language with optional function arguments protects you from this sort of behavior?
Languages with a sane type system.
TypeScript has no issues catching such mistakes. Writing tests to catch simple type errors is such an incredible waste of time.
- tom_mellior 6y agoThe article has a whole section called "TypeScript doesn't solve this", with examples and stuff. Is it mistaken?
- sfvisser 6y agoPartially. TypeScript doesn't complain when you pass in a function that ignores some of its arguments. Which is totally fine and safe. If you upgrade your function from no second argument to a numeric second argument TypeScript will not complain and your program might break. It will not crash, because it still perfectly type-safe, but it might not behave like you want to. So in that sense the article has a point. However, this is just one instance of a larger issue with changing the behavior of a function, while keeping the types compatible. - Using a function as a callback to .map() with two numeric arguments and then swapping the arguments. - Returning a tuple of two of the same type and swapping the order. - Returning a string in a new encoding. - ... Basic rule: if it's a type error and the program might crash, TypeScript will complain. If the types are fine and only the behavior changes, TypeScript will (obviously) not complain. Callback functions and optional arguments are not special in this regard.
- macintux 6y ago> It will not crash, because it still perfectly type-safe, but it might not behave like you want to. Which is generally worse than crashing, because silent data corruption can have far-reaching impacts.
- tom_mellior 6y agoThanks for the explanation. > If you upgrade your function from no second argument to a numeric second argument [...] It will not crash, because it still perfectly type-safe It's type-safe using a definition of "type-safe" that is defined relative to the underlying JavaScript model of "corrupt the user's data rather than crash". It wouldn't be type-safe using most other languages' (including Python, for example) model of "functions have a type that includes the number of arguments, and applying them to the wrong number of arguments is meaningless and hence not considered type-safe". It's fair for TypeScript to use this approach. But it is surprising to many of us, who view type systems as tools for ruling out some dumb functional bugs, not just crashes.