JavaScript

TypeScript

TypeScript is JavaScript with Type checking. A superset of JS. First learned in CS349.

From CS349

  • Main feature added: static types
  • typescript is statically typed
    • performs type checking at compile time
    • once we assign a variable a type, we can’t change it

JavaScript with Type Checking”

  • TypeScript is a superset of JavaScript
  • Developed by Microsoft starting in 2012
    • Led by Anders Hejlsberg (creator of C# and Turbo Pascal)
    • Took off in 2014 (when Angular 2 chose TypeScript)
  • Main feature is adding static types
    • enables type checking
    • enables code completion

TypeScript is transpile to JavaScript in order to run in the browser. remember the browser only executes JavaScript

  • Our Vite setup lets you debug TypeScript source
    • but you’re debugging JavaScript from a TypeScript “source map”
  • Most TypeScript tutorials show how to install the tsc compiler
    • Our Vite dev environment already transpiles to TypeScript, there is no need to install/call tsc
  • ES Module

Types

  • TypeScript types are annotations
    • checked at “compile” time, not run time

Avoid the any type

Caution: implicit type inference can result in the any type!

Use CamelCase for type aliases (I always forget…)

Variable Typing and the Any Type

  • When you don’t give the variable an explicit type annotation, or an initial value so it can do implicit type inference, it’s the any type
  • The any type turns off typescript’s type checking

Array, Object, Function, Interface Typing

Structural Type Checking

  • Only the structure of a type matters
  • If an object has the parameter we need, in the order we need it, nothing else is relevant

Optional Parameters

  • Denoted by ?
  • Type narrowing is usually required

Enums vs. Literal Types