Type Annotations in JavaScript

Type Annotations in JavaScript

ECMAScript TC39 Proposal - Stage 1 - June 2022

Motivation

  • ‚ÄčStatic type checking has proven fairly successful!
  • Tools: Google's Closure Compiler, Facebook's Flow and Microsoft's TypeScript
  • Bring productivity-gains as seen in other statically-typed languges to JavaScript
  • Catch errors early on
  • Leverage editor tooling
  • Proposal

Community Usage and Demand - State of JS Survey

Trends in JavaScript Compilation

  • ‚ÄčTranspilation of JavaScript necessary to use modern language features, but still support "legacy" browsers
  • So, a build step is already present. Why not introduce type checking during build?
  • Citation from proposal: "This proposal will reduce the need to have a build step which can make some development set-ups much simpler. Users can simply run the code they wrote."

Type Annotations Syntax

let x: string; x = "hello"; x = 100; function equals(x: number, y: number): boolean { return x === y; }

Type Declaration Syntax

interface Person { name: string; age: number; } type CoolBool = boolean; // Classes as Type Declarations class Person { name: string; constructor(name: string) { this.name = name; } getGreeting(): string { return `Hello, my name is ${this.name}`; } }

Kinds of Types

// Types References with Type Arguments Set<string> // Object Types { name: string, age: number } // Callable Type Shorthand (x: string) => string // Constructable Type Shorthand new (n: Bread) => Duck // Tuple Types [number, number] // Union Types string | number // Intersection Types Named & Dog // Indexed Access Types T[K]

Interesting FAQs

Does JavaScript need static type-checking?
=> Given how much effort organizations and teams have put into building type-checkers and adopting them, the answer is yes.

Why not stick to existing JS comment syntax?
=> Although it is possible to define types in existing JavaScript comments, as Closure and TypeScript's JSDoc mode do, this syntax is much more verbose and unergonomic.

Does this proposal make all TypeScript programs valid JavaScript?
=> Most constructs in TypeScript are compatible, but not all, and most of those that do not pass can be converted via simple codemod changes that can make them both TypeScript-compatible and compatible with this proposal.

Static Analysis Only - No Change To Runtime Behavior

The proposal to add type-annotations to JavaScript aims to introduce no change to the current runtime behavior of JavaScript.

A helpful mental model is to understand type-annotations similar to comments. They are not evaluated by the interpreter.


Link to the Proposal