@traversymediaNoteUpdated November 23, 2026
TypeScript Crash Course: Commands and Code
Every command and code snippet from the TypeScript Crash Course, in video order.
TypeScript Crash Course: Commands and Code
This is the companion to my TypeScript video. 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:
mkdir learn-ts
cd learn-ts
npm init -y
npm pkg set type=moduleThe 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:
function double(n: number): number {
return n * 2;
}This is what actually runs, with the types stripped out:
function double(n) {
return n * 2;
}2. Running TypeScript
Install TypeScript and the types for Node:
npm install -D typescript @types/nodeTypeScript's settings go in tsconfig.json. You can generate one:
npx tsc --initThis is the one in the video. If you generated one, replace what's in it with this:
{
"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:
let title = 'Learn TypeScript';
let count = 3;
console.log(title, count);Run it with Node:
node basics.tsLearn TypeScript 3Check the types. No output means no errors:
npx tsc3. Inference and Annotations
Hover over the variables in basics.ts to see the types TypeScript worked out:
let title: string
let count: numberAdd this line above the console.log:
count = 'three';It's an error in your editor:
Type 'string' is not assignable to type 'number'.But Node still runs it, because Node only removes types:
node basics.tsLearn TypeScript threenpx tsc is what catches it:
npx tscbasics.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:
function addTask(title, priority) {
return `${priority}. ${title}`;
}Parameter 'title' implicitly has an 'any' type.Replace it with the annotated version:
function addTask(
title: string,
priority: number,
) {
return `${priority}. ${title}`;
}Hover over addTask, and TypeScript worked out that it returns a string:
function addTask(title: string, priority: number): stringCall it with the word high for the priority, and you get an error. Take the line out once you've seen it:
addTask('Set up Node', 'high');Argument of type 'string' is not assignable to parameter of type 'number'.A function that never returns:
function fail(message: string): never {
throw new Error(message);
}4. Unions and Literal Types
Create task.ts:
type Status = 'todo' | 'done';
function setStatus(status: Status) {
console.log(`Status is now ${status}`);
}
setStatus('done');Adding a status means changing one line:
type Status = 'todo' | 'in-progress' | 'done';A typo is an error:
setStatus('dne');Argument of type '"dne"' is not assignable to parameter of type 'Status'.5. any
Replace everything in task.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:
node task.tsStatus is now 42
TypeError: value.toUpperCase is not a function6. Objects and Arrays
Replace everything in task.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:
const task: Task = {
id: 1,
title: 'Learn TypeScript',
};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:
const task: Task = {
id: 1,
title: 'Learn TypeScript',
status: 'todo',
};Replace task with an array of tasks:
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:
interface Task {
id: number;
title: string;
status: Status;
notes?: string;
}Add an intersection to the bottom of task.ts:
type TaskWithDue = Task & { due: string };A TaskWithDue without a due date is an error:
const report: TaskWithDue = {
id: 4,
title: 'Send the report',
status: 'todo',
};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:
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:
interface TaskWithDue extends Task {
due: string;
}8. Functions
Take TaskWithDue and report out of task.ts, and add this below the tasks array:
function makeTask(
title: string,
notes?: string,
): Task {
return {
id: tasks.length + 1,
title,
status: 'todo',
notes,
};
}Returning just the title instead is an error:
return title;Type 'string' is not assignable to type 'Task'.Add a function that doesn't return anything, then use them both:
function logTask(task: Task): void {
console.log(`${task.id}. ${task.title}`);
}
tasks.push(makeTask('Pay rent'));
tasks.forEach(logTask);node task.ts1. Read docs
2. Set up Node
3. Pay rentHere'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:
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:
function formatId(id: string | number) {
return id.toUpperCase();
}Property 'toUpperCase' does not exist on type 'string | number'.Replace it with a version that checks first:
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:
(parameter) id: string
(parameter) id: numbernode narrowing.tsABC #710. Data From Outside
Create data.ts. Here we trust the data with as:
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:
const data: anyBut it crashes when you run it:
node data.tsTypeError: Cannot read properties of undefined (reading 'toUpperCase')Replace it with unknown, and using it without checking is an error:
import type { Task } from './task.ts';
const text = '{"id": 3, "name": "Call mom"}';
const data: unknown = JSON.parse(text);
console.log(data.title);'data' is of type 'unknown'.Check it first, and the error's gone:
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');
}node data.tsThat is not a task11. Generics
Create generics.ts. With any, TypeScript loses track of the type:
import { tasks } from './task.ts';
function first(items: any[]) {
return items[0];
}
const firstTask = first(tasks);Hover over firstTask:
const firstTask: anyReplace it with a generic, and the type follows the data through:
import { tasks } from './task.ts';
function first<T>(items: T[]): T | undefined {
return items[0];
}
const firstTask = first(tasks);
const firstNumber = first([1, 2, 3]);Hover over both:
const firstTask: Task | undefined
const firstNumber: number | undefined12. Utility Types
Create utility.ts. A new task leaves out the id, so giving it one is an error:
import type { Task } from './task.ts';
type NewTask = Omit<Task, 'id'>;
const draft: NewTask = {
id: 5,
title: 'Pay rent',
status: 'todo',
};Object literal may only specify known properties, and 'id' does not exist in type 'NewTask'.Here's the finished file:
import type { Task } from './task.ts';
type NewTask = Omit<Task, 'id'>;
const draft: NewTask = {
title: 'Pay rent',
status: 'todo',
};
const changes: Partial<Task> = {
status: 'done',
};
type TaskPreview = Pick<Task, 'id' | 'title'>;
type FullTask = Required<Task>;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:
npm create vite@latest task-app -- --template react-ts
cd task-app
npm install
npm run devThe starter's src/main.tsx uses ! to say the root element isn't null:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)And its build script checks the types, then strips them:
"build": "tsc -b && vite build"Create src/types.ts, which the video doesn't show:
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 <input:
import type { Task } from './types';
type TaskListProps = {
tasks: Task[];
onToggle: (id: number) => void;
};
function TaskList({ tasks, onToggle }: TaskListProps) {
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>
<input
type="checkbox"
checked={task.status === 'done'}
onChange={() => onToggle(task.id)}
/>
{task.title}
</li>
))}
</ul>
);
}
export default TaskList;Replace src/App.tsx. Using TaskList without onToggle is an error:
import { useState } from 'react';
import TaskList from './TaskList';
import type { Task } from './types';
function App() {
const [tasks] = useState<Task[]>([]);
return <TaskList tasks={tasks} />;
}
export default App;Property 'onToggle' is missing in type '{ tasks: Task[]; }' but required in type 'TaskListProps'.Here's the finished src/App.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<Task[]>([]);
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<HTMLInputElement>,
) {
setTitle(event.target.value);
}
return (
<main>
<h1>Tasks</h1>
<input value={title} onChange={handleChange} />
<button onClick={addTask}>Add</button>
<TaskList tasks={tasks} onToggle={toggleTask} />
</main>
);
}
export default App;Take <Task[]> off the first useState, and adding a task is an error:
const [tasks, setTasks] = useState([]);const tasks: never[]
Type 'Task' is not assignable to type 'never'.Hover over onChange to see the event type it wants:
(property) React.InputHTMLAttributes<HTMLInputElement>.onChange?: React.ChangeEventHandler<HTMLInputElement, HTMLInputElement> | undefined