Introduction to Typescript
Typescript
- A statically typed
superset
of JavaScript that compiles to plain JavaScript.- Any valid JavaScript, is valid Typescript
- TypeScript adds additional developer features to JavaScript that are stripped away at compile time
- TypeScript is a static type checker
- Detects errors in code without running it
- TypeScript does NOT effect the runtime behavior of JavaScript
- To run TypeScript code, we have to convert it to JavaScript FIRST
- The TypeScript to JavaScript compilation process removes all type information
- TypeScript doesnโt provide any additional runtime libraries. Thereโs no additional TypeScript-specific framework to learn.
- Should I learn JavaScript or TypeScript first?
Prerequisites
- You have built basic web pages or backends with JavaScript
- You have
npm
andnode
installed
Agenda
- Project Setup
- create
package.json
npm init -y
- install
typescript
as dev dependencynpm i -D typescript
- create / update
tsconfig.json
- install
nodemon
andts-node
npm i -D nodemon ts-node
- add scripts to
package.json
- build, dev, start
- create
- Type Annotations
- Inferred Types
- Union Types
- Objects and Interfaces
- Optional Properties
- "duck typing" or "structural typing"
- As long as the object has the same shape, it is considered the same type
- Classes
- Generics
- How to read / fix errors
- Generate Typescript Interfaces from JSON / API Responses
Examples
We'll use project templates for these so we don't have to configure typescript from scratch.
- Typescript with Express
npx create-express-api --typescript --directory my-api-name
- API contract with express + axios
- Typescript with react
npm create vite@latest -- --template react-ts
- Typescript with Vue
npm create vite@latest -- --template vue-ts
- Usage with composition API
- Anything on npm will work (within reason)