Why TypeScript is useful
I can say why I think TypeScript could be useful. But it's only when I personally find a use for something that I really understand why it's useful.
In my code I had a function that set the number of decimal places of a number. Here's a simplified version in JavaScript:
const setDP = (key) => {
return key.toFixed(2);
};
This takes in 'key', changes it to have 2 decimal places, then returns it. Perfectly fine and you might be wondering what the problem with that is. Well, TypeScript told me...
Here's the same code in TypeScript:
const setDP = (key: number): number => {
return key.toFixed(2);
};
All I've said here is that key is a number and the function returns a number. Which is what we want. But it's not what we're getting. TypeScript immediately complains that I've said the function is returning a number, but it's returning a string.
Which is crazy, surely toFixed returns a number. But no, MDN clearly states otherwise:
toFixed() returns a string representation of numObj
I needed my return value to be a number, due to things I was doing with it later. If I hadn't been using TypeScript I'd have spent time trying to find the problem. TypeScript told me exactly what the problem was, so I could fix it.
I've been using it for a little while, as I knew, in the abstract, that it was useful. Now I'm a convert.