# TypeScript Crash Course: Commands and Code This is the companion to [my TypeScript video](https://www.youtube.com/watch?v=NNS4a9_nY44). It has the commands we run and the code from the editor, in the same order as the video, so you can try it yourself. The explaining is in the video. You need Node.js 22.18 or later, which runs TypeScript files directly. ## Setup This part isn't in the video. Make a folder to work in: ```bash mkdir learn-ts cd learn-ts npm init -y npm pkg set type=module ``` The last command is what lets the files import from each other later on. ## 1. What Is TypeScript `double.ts` has a type on the parameter and a type for what it returns. The rest is plain JavaScript: ```ts function double(n: number): number { return n * 2; } ``` This is what actually runs, with the types stripped out: ```js function double(n) { return n * 2; } ``` ## 2. Running TypeScript Install TypeScript and the types for Node: ```bash npm install -D typescript @types/node ``` TypeScript's settings go in `tsconfig.json`. You can generate one: ```bash npx tsc --init ``` This is the one in the video. If you generated one, replace what's in it with this: ```json { "compilerOptions": { "module": "nodenext", "types": ["node"], "noEmit": true, "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "erasableSyntaxOnly": true } } ``` Strict mode is on by default from TypeScript 6, so this doesn't set it. On older versions, add `"strict": true`. Create `basics.ts`: ```ts let title = 'Learn TypeScript'; let count = 3; console.log(title, count); ``` Run it with Node: ```bash node basics.ts ``` ```text Learn TypeScript 3 ``` Check the types. No output means no errors: ```bash npx tsc ``` ## 3. Inference and Annotations Hover over the variables in `basics.ts` to see the types TypeScript worked out: ```text let title: string let count: number ``` Add this line above the `console.log`: ```ts count = 'three'; ``` It's an error in your editor: ```text Type 'string' is not assignable to type 'number'. ``` But Node still runs it, because Node only removes types: ```bash node basics.ts ``` ```text Learn TypeScript three ``` `npx tsc` is what catches it: ```bash npx tsc ``` ```text basics.ts:4:1 - error TS2322: Type 'string' is not assignable to type 'number'. ``` Take that line back out. Then add this function to the bottom of the file. Both parameters get an error: ```ts function addTask(title, priority) { return `${priority}. ${title}`; } ``` ```text Parameter 'title' implicitly has an 'any' type. ``` Replace it with the annotated version: ```ts function addTask( title: string, priority: number, ) { return `${priority}. ${title}`; } ``` Hover over `addTask`, and TypeScript worked out that it returns a string: ```text function addTask(title: string, priority: number): string ``` Call it with the word high for the priority, and you get an error. Take the line out once you've seen it: ```ts addTask('Set up Node', 'high'); ``` ```text Argument of type 'string' is not assignable to parameter of type 'number'. ``` A function that never returns: ```ts function fail(message: string): never { throw new Error(message); } ``` ## 4. Unions and Literal Types Create `task.ts`: ```ts type Status = 'todo' | 'done'; function setStatus(status: Status) { console.log(`Status is now ${status}`); } setStatus('done'); ``` Adding a status means changing one line: ```ts type Status = 'todo' | 'in-progress' | 'done'; ``` A typo is an error: ```ts setStatus('dne'); ``` ```text Argument of type '"dne"' is not assignable to parameter of type 'Status'. ``` ## 5. any Replace everything in `task.ts`: ```ts type Status = 'todo' | 'done'; function setStatus(status: Status) { console.log(`Status is now ${status}`); } let value: any = 'todo'; value = 42; setStatus(value); value.toUpperCase(); ``` There are no errors, but it crashes when you run it: ```bash node task.ts ``` ```text Status is now 42 TypeError: value.toUpperCase is not a function ``` ## 6. Objects and Arrays Replace everything in `task.ts`: ```ts type Status = 'todo' | 'done'; type Task = { id: number; title: string; status: Status; notes?: string; }; ``` Add a task without a status, and it's an error: ```ts const task: Task = { id: 1, title: 'Learn TypeScript', }; ``` ```text Property 'status' is missing in type '{ id: number; title: string; }' but required in type 'Task'. ``` Replace it with one that has a status, and it's gone: ```ts const task: Task = { id: 1, title: 'Learn TypeScript', status: 'todo', }; ``` Replace `task` with an array of tasks: ```ts const tasks: Task[] = [ { id: 1, title: 'Read docs', status: 'todo' }, { id: 2, title: 'Set up Node', status: 'done', notes: 'Took two minutes', }, ]; ``` ## 7. Interfaces and Intersections Replace `type Task` with an interface: ```ts interface Task { id: number; title: string; status: Status; notes?: string; } ``` Add an intersection to the bottom of `task.ts`: ```ts type TaskWithDue = Task & { due: string }; ``` A `TaskWithDue` without a due date is an error: ```ts const report: TaskWithDue = { id: 4, title: 'Send the report', status: 'todo', }; ``` ```text Property 'due' is missing in type '{ id: number; title: string; status: "todo"; }' but required in type '{ due: string; }'. ``` Replace `report` with one that has it: ```ts const report: TaskWithDue = { id: 4, title: 'Send the report', status: 'todo', due: 'Friday', }; ``` To write the same thing with an interface, replace `type TaskWithDue` with this: ```ts interface TaskWithDue extends Task { due: string; } ``` ## 8. Functions Take `TaskWithDue` and `report` out of `task.ts`, and add this below the `tasks` array: ```ts function makeTask( title: string, notes?: string, ): Task { return { id: tasks.length + 1, title, status: 'todo', notes, }; } ``` Returning just the title instead is an error: ```ts return title; ``` ```text Type 'string' is not assignable to type 'Task'. ``` Add a function that doesn't return anything, then use them both: ```ts function logTask(task: Task): void { console.log(`${task.id}. ${task.title}`); } tasks.push(makeTask('Pay rent')); tasks.forEach(logTask); ``` ```bash node task.ts ``` ```text 1. Read docs 2. Set up Node 3. Pay rent ``` Here's the finished `task.ts`. It also has `export` in front of `Task` and `tasks`, which the video doesn't show, because the next files import them: ```ts type Status = 'todo' | 'done'; export interface Task { id: number; title: string; status: Status; notes?: string; } export const tasks: Task[] = [ { id: 1, title: 'Read docs', status: 'todo' }, { id: 2, title: 'Set up Node', status: 'done', notes: 'Took two minutes', }, ]; function makeTask( title: string, notes?: string, ): Task { return { id: tasks.length + 1, title, status: 'todo', notes, }; } function logTask(task: Task): void { console.log(`${task.id}. ${task.title}`); } tasks.push(makeTask('Pay rent')); tasks.forEach(logTask); ``` ## 9. Narrowing Create `narrowing.ts`. This is an error, because numbers don't have `toUpperCase`: ```ts function formatId(id: string | number) { return id.toUpperCase(); } ``` ```text Property 'toUpperCase' does not exist on type 'string | number'. ``` Replace it with a version that checks first: ```ts function formatId(id: string | number) { if (typeof id === 'string') { return id.toUpperCase(); } return `#${id}`; } console.log(formatId('abc'), formatId(7)); ``` Hover over `id` inside the if, then after it: ```text (parameter) id: string (parameter) id: number ``` ```bash node narrowing.ts ``` ```text ABC #7 ``` ## 10. Data From Outside Create `data.ts`. Here we trust the data with `as`: ```ts import type { Task } from './task.ts'; const text = '{"id": 3, "name": "Call mom"}'; const data = JSON.parse(text); const task = data as Task; console.log(task.title.toUpperCase()); ``` There are no errors, because `data` is any: ```text const data: any ``` But it crashes when you run it: ```bash node data.ts ``` ```text TypeError: Cannot read properties of undefined (reading 'toUpperCase') ``` Replace it with `unknown`, and using it without checking is an error: ```ts import type { Task } from './task.ts'; const text = '{"id": 3, "name": "Call mom"}'; const data: unknown = JSON.parse(text); console.log(data.title); ``` ```text 'data' is of type 'unknown'. ``` Check it first, and the error's gone: ```ts import type { Task } from './task.ts'; const text = '{"id": 3, "name": "Call mom"}'; const data: unknown = JSON.parse(text); if ( typeof data === 'object' && data !== null && 'title' in data ) { console.log(data.title); } else { console.log('That is not a task'); } ``` ```bash node data.ts ``` ```text That is not a task ``` ## 11. Generics Create `generics.ts`. With `any`, TypeScript loses track of the type: ```ts import { tasks } from './task.ts'; function first(items: any[]) { return items[0]; } const firstTask = first(tasks); ``` Hover over `firstTask`: ```text const firstTask: any ``` Replace it with a generic, and the type follows the data through: ```ts import { tasks } from './task.ts'; function first(items: T[]): T | undefined { return items[0]; } const firstTask = first(tasks); const firstNumber = first([1, 2, 3]); ``` Hover over both: ```text const firstTask: Task | undefined const firstNumber: number | undefined ``` ## 12. Utility Types Create `utility.ts`. A new task leaves out the id, so giving it one is an error: ```ts import type { Task } from './task.ts'; type NewTask = Omit; const draft: NewTask = { id: 5, title: 'Pay rent', status: 'todo', }; ``` ```text Object literal may only specify known properties, and 'id' does not exist in type 'NewTask'. ``` Here's the finished file: ```ts import type { Task } from './task.ts'; type NewTask = Omit; const draft: NewTask = { title: 'Pay rent', status: 'todo', }; const changes: Partial = { status: 'done', }; type TaskPreview = Pick; type FullTask = Required; ``` ## 13. TypeScript in React Create a React project with Vite. Run this outside the `learn-ts` folder, or `npx tsc` in there will check the React files too: ```bash npm create vite@latest task-app -- --template react-ts cd task-app npm install npm run dev ``` The starter's `src/main.tsx` uses `!` to say the root element isn't null: ```tsx import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' import App from './App.tsx' createRoot(document.getElementById('root')!).render( , ) ``` And its build script checks the types, then strips them: ```json "build": "tsc -b && vite build" ``` Create `src/types.ts`, which the video doesn't show: ```ts export type Status = 'todo' | 'done'; export interface Task { id: number; title: string; status: Status; notes?: string; } ``` Create `src/TaskList.tsx`. The video shows it down to the ` void; }; function TaskList({ tasks, onToggle }: TaskListProps) { return (
    {tasks.map((task) => (
  • onToggle(task.id)} /> {task.title}
  • ))}
); } export default TaskList; ``` Replace `src/App.tsx`. Using `TaskList` without `onToggle` is an error: ```tsx import { useState } from 'react'; import TaskList from './TaskList'; import type { Task } from './types'; function App() { const [tasks] = useState([]); return ; } export default App; ``` ```text Property 'onToggle' is missing in type '{ tasks: Task[]; }' but required in type 'TaskListProps'. ``` Here's the finished `src/App.tsx`: ```tsx import { useState } from 'react'; import type { ChangeEvent } from 'react'; import TaskList from './TaskList'; import type { Task } from './types'; function App() { const [tasks, setTasks] = useState([]); const [title, setTitle] = useState(''); function toggleTask(id: number) { setTasks( tasks.map((task) => { if (task.id !== id) return task; const status = task.status === 'todo' ? 'done' : 'todo'; return { ...task, status }; }), ); } function addTask() { const task: Task = { id: Date.now(), title, status: 'todo', }; setTasks([...tasks, task]); setTitle(''); } function handleChange( event: ChangeEvent, ) { setTitle(event.target.value); } return (

Tasks

); } export default App; ``` Take `` off the first `useState`, and adding a task is an error: ```tsx const [tasks, setTasks] = useState([]); ``` ```text const tasks: never[] Type 'Task' is not assignable to type 'never'. ``` Hover over `onChange` to see the event type it wants: ```text (property) React.InputHTMLAttributes.onChange?: React.ChangeEventHandler | undefined ```