Intro to

TypeScript

Intro to TypeScript

Course repository: https://github.com/moonhighway/intro-to-typescript

 

Required: Node.js >= v18.0.0

Recommended: Visual Studio Code (with GitHub Copilot disabled)

 

Setup

If you've already cloned the repository, bring it up-to-date:

  git pull

Then install dependencies by running:

  npm install

Types of activity

  • 😲 Slides & Samples: I show you amazing things!
  • 💪🏻 Exercise: We code together and practice what we’ve just learnt.
    • Steps are in the README.md for the exercise if you need them at any point.
  • 🧑‍🔬 Lab: Tackle a coding challenge by yourself. After we review a solution.
    • Lab requirements are in the README.md for each lab.

Goals

  • Learn what TypeScript is and how to use it
  • Configure a TypeScript project
  • Get comfortable with the fundamentals
  • Tackle common "gotchas" when using TypeScript

Section 1: A World of Types

What is TypeScript?

  • "TypeScript is JavaScript with syntax for types"
  • Strongly typed programming language
  • Released publicly by Microsoft in 2012
  • TypeScript = JavaScript + types
let myFavoriteFood = 'Pozole Rojo';
let myFavoriteFood: string = 'Pozole Rojo';

Types: Basic Types

  • Top types (represent any value): unknown, any
  • Types which correspond to JavaScript primitives:
    • string, number, bigint, boolean, symbol
    • null, undefined
  • Bottom type (represents state which shouldn't exist): never

Types: Objects

Anonymous object type

const boat: {
  name: string;
  length: number;
  atSea: boolean;
} = {
  name: "S. S. Minnow",
  length: 30,
  atSea: false,
};

Types: Objects

Interface declaration

interface Boat {
  name: string;
  length: number;
  atSea: boolean;
}

Types: Objects

Type alias

type Boat = {
  name: string;
  length: number;
  atSea: boolean;
};

Types: Objects

Property modifiers

? for optional properties

readonly for immutable properties

Types: Objects

Interfaces vs Type aliases: Which to use?

  • Interfaces are open, type aliases are closed
  • Interfaces can provide slightly better error messages
  • Use type aliases unless you have a reason not to

Types: Arrays

Square bracket syntax

const populations: number[] = [
  8537673,
  2140526,
  3769495
];

Types: Arrays

The Array type

const populations: Array<number> = [
  8537673,
  2140526,
  3769495
];

Types: Arrays

Tuple type for fixed length arrays

const highestTemperature: [string, number] = [
  'Vancouver',
  34.4
];

Benefits of TypeScript

  • “The main benefit of TypeScript is that it can highlight unexpected behavior in your code, lowering the chance of bugs.
    — TypeScript docs
  • Types as a form of documentation
  • Safer code refactoring
  • Can use types as a contract between different parts of our applications
  • Visual Studio Code
    • Problems panel
    • 'Go to Type Definition'
  • Editors such as WebStorm and Sublime Text also have built-in support for TypeScript
  • Other editors provide TypeScript support via extensions or plugins

Code Editor Integration

How do we run TypeScript code?

  • We don't, we compile it!
  • TypeScript code compiles to JavaScript
  • Types are stripped away at compile time
  • Then we run the compiled JavaScript

TypeScript Project Configuration

Compilation & Execution

Tools that can compile TypeScript

TypeScript compiler: tsc
Bundlers: Vite, esbuild, swc

Tools that compile TypeScript and run the code

JavaScript runtimes: Deno, Bun
TypeScript code runners: tsx, tsm, ts-node

Section 2: Types in Action

Functions

  • Parameter types
  • Return types
  • async function return types: Promise<Type>

Union types

  • Pipe operator: |
  • string | number
  • Anywhere you can put a type, you can put a union type

Type Narrowing

  • typeof type guard
  • Truthiness narrowing
    • Equality narrowing, for example: ===
    • instanceof type guard

Error Handling

  • In a try...catch statement, TypeScript infers errors as any
  • Type for error in a catch block can only be declared as any or unknown
  • Use unknown as it gives us type safety

Section 3: Flexible Types

Extending object types

Extending an interface

interface Comment {
  id: string;
  body: string;
}

interface ApprovedComment extends Comment {
  approved: boolean;
}
interface X extends Y { ... }

Intersection Types: &

Object index signatures

type StringArray = {
  [index: number]: string;
}

type NumberDictionary = {
  [index: string]: number;
}

When you don't know the names of an object's properties, but know what the types should be.

typeof Type Operator

export and import

Type Declarations: .d.ts

  1. Add types into project code that we write
  2. Built-in to third-party package
  3. Provided by an @types packages (DefinitelyTyped project)

Agenda: Part 2

  • 09:00am: Generics (1h)
  • 10:00am: Break (15m)
  • 10:15am: Classes (1h)
  • 11:15am: Break (15m)
  • 11:30am: Debugging TypeScript (1.5h)
  • 01:00pm: Wrap up

TypeScript Pain? ❤️‍🩹

Share it here and let's debug it together!

https://forms.gle/oxvTBFmuLNiwXLy37

Section 4: Generics

Generics

"Generics" in TypeScript

Things which are generic.

Generics

Things which can be generic

Functions   function someFunction(){...}
Classes     class SomeClass(){...}
Types       type SomeType = {...}

Generics

Type parameters

Functions   function someFunction<Type>(){...}
Classes     class SomeClass()<Type>{...}
Types       type SomeType<Type> = {...}

Adding a type parameter makes the "thing" generic!  

Utility Types

  • Built-in generic types
  • Globally available in TypeScript

Partial<Type>

Required<Type>

Readonly<Type>

ReadonlyArray<Type>

Pick<Type, Keys>

Omit<Type, Keys>

Record<Keys, Type>

...and more!

Section 5: Classes

Classes

Classes in JavaScript

class Country {
  name;
  code;
}

Classes

TypeScript: Field modifiers

class Country {
  readonly name;
  private code;
}

Classes

TypeScript: Generic classes

class Country<CodeType> {
  name;
  code: CodeType;
}

Section 6:
Debugging TypeScript

Type Errors

  • Read complex error messages from the bottom up.
  • Look up errors by their code at https://typescript.tv/errors/
  • Tip: 'Restart TS Server' command in Visual Studio Code (when you have a TypeScript file open)

Debugging TypeScript

// @ts-ignore         Suppress any type errors on next line.

Comment directives

// @ts-expect-error   Error if next line doesn't have error.

// @ts-nocheck        Disable type checking for a file.

VS Code Extensions

Intro to TypeScript

By Moon Highway

Intro to TypeScript

  • 57