Validating perfectly at run time is exceedingly difficult and tedious. Does anyone actually write defensive code like this?:
function sum(arr) {
if (!Array.isArray(arr))
throw "Invalid type";
let result = 0;
for (const val of arr) {
if (typeof val != "number")
throw "Invalid type";
result += val;
}
return result;
}
By contrast, the TypeScript code is reasonable: function sum(arr: Array<number>) {
let result: number = 0;
for (const val of arr)
result += val;
return result;
}
> it does make the code more terseNo, TypeScript code with explicit type annotations is less terse than the typical unsafe JavaScript code that lacks type checks.
> It requires that you define types for every little thing
No, the TypeScript compiler has type inference. It can assign types based on how values are passed between known functions. While it's a good idea to explicitly type all function signatures in TypeScript, it's not mandatory unlike Rust.
Setting the type of unknown data to `unknown` forces you to validate it.
The incompatible changes are more likely caught at compile time, and far less likely to become apparent only when deployed.
That said, also TS itself is not fool proof - there are times where the config in use (strict vs. non strict null checks) and other factors (e.g. de-serialising JSON) can mean that your data does not in fact match the expected types.
You're confusing runtime checks with compile time checks. If you mess types while developing, you will know instantly with TypeScript but you'll find out during testing with JavaScript (or in production)
I don't agree. 99% of javascript/typescript programs will be dealing with data that is potentially null and without strict compile time type checking that typescript affords writing correct javascript programs is almost impossible.
It's tedious but it's far from impossible.