DEV Community

Discussion on: TypeScript is a waste of time. Change my mind.

Collapse
 
calvintwr profile image
calvintwr • Edited

I think fundamentally, the extent of the discussions suggest we probably all agree that an argument has to be within what is intended for a function to handle.

Notice I wrote “within what is intended”, and not whether it is of the correct type. Type is only one dimension, fiercely focused upon, and I very much agree rightfully so. But could it have inadvertently cause other dimensions such as range —which is perhaps just as important — to be grossly overlooked. Perhaps more often than not, it’s the consequence of the latter that is so hard to debug. I illustrate:

(1) It is usually not just a matter of type, but also the range of value that your function can handle, e.g

function howManyDigitsInAnInteger(integer) {
    return parseInt(Math.log(integer))
}

The above function looks fine, but actually, integer has to be between 0 to 999999999999997 for the function to work! So this function has a limit before it starts going cranky. The problem is that function silently appears to work normally. A programmer might be alluded to think, “I have strict typing, things won’t go wrong”. But the range... we forgot about the range.
(Although you also have to check whether a proper integer was given, and not number with decimal point, but I think that’s one level above type and range checking. So that can be checked with some code within the function.)

And (2) in the world of JSON, everything is a string, so it’s most practical for a mathematical function to handle both Numbers and also strings that are actually numbers. So if we use the previous example, what you really need is a function that will throw error if the argument is not a string or an integer, is a string that cannot be converted to an integer, and/or the result of which is not within 0 to 999999999999997.

It was never just about type. Its about type, and range, and externality (knowing that the transport layer can mess up object typing).

A validation library comes close: github.com/sindresorhus/ow

But perhaps we all need to shift away from so doggedly fighting over whether to type or not to type, than to move one and recognise that it’s more that just type, and perhaps build something better for the future.