Comment

Comment by nayuki

> vanilla JavaScript that validates function arguments properly

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 terse

No, 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.

parent nayuki 5 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton