@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:

Bash / Shell
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:

TypeScript
function double(n: number): number {
  return n * 2;
}

This is what actually runs, with the types stripped out:

JavaScript
function double(n) {
  return n * 2;
}

2. Running TypeScript

Install TypeScript and the types for Node:

Bash / Shell
npm install -D typescript @types/node

TypeScript's settings go in tsconfig.json. You can generate one:

Bash / Shell
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:

TypeScript
let title = 'Learn TypeScript';
let count = 3;

console.log(title, count);

Run it with Node:

Bash / Shell
node basics.ts
Plain Text
Learn TypeScript 3

Check the types. No output means no errors:

Bash / Shell
npx tsc

3. Inference and Annotations

Hover over the variables in basics.ts to see the types TypeScript worked out:

Plain Text
let title: string
let count: number

Add this line above the console.log:

TypeScript
count = 'three';

It's an error in your editor:

Plain Text
Type 'string' is not assignable to type 'number'.

But Node still runs it, because Node only removes types:

Bash / Shell
node basics.ts
Plain Text
Learn TypeScript three

npx tsc is what catches it:

Bash / Shell
npx tsc
Plain 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:

TypeScript
function addTask(title, priority) {
  return `${priority}. ${title}`;
}
Plain Text
Parameter 'title' implicitly has an 'any' type.

Replace it with the annotated version:

TypeScript
function addTask(
  title: string,
  priority: number,
) {
  return `${priority}. ${title}`;
}

Hover over addTask, and TypeScript worked out that it returns a string:

Plain 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:

TypeScript
addTask('Set up Node', 'high');
Plain Text
Argument of type 'string' is not assignable to parameter of type 'number'.

A function that never returns:

TypeScript
function fail(message: string): never {
  throw new Error(message);
}

4. Unions and Literal Types

Create task.ts:

TypeScript
type Status = 'todo' | 'done';

function setStatus(status: Status) {
  console.log(`Status is now ${status}`);
}

setStatus('done');

Adding a status means changing one line:

TypeScript
type Status = 'todo' | 'in-progress' | 'done';

A typo is an error:

TypeScript
setStatus('dne');
Plain Text
Argument of type '"dne"' is not assignable to parameter of type 'Status'.

5. any

Replace everything in task.ts:

TypeScript
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 / Shell
node task.ts
Plain Text
Status is now 42
TypeError: value.toUpperCase is not a function

6. Objects and Arrays

Replace everything in task.ts:

TypeScript
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:

TypeScript
const task: Task = {
  id: 1,
  title: 'Learn TypeScript',
};
Plain 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:

TypeScript
const task: Task = {
  id: 1,
  title: 'Learn TypeScript',
  status: 'todo',
};

Replace task with an array of tasks:

TypeScript
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:

TypeScript
interface Task {
  id: number;
  title: string;
  status: Status;
  notes?: string;
}

Add an intersection to the bottom of task.ts:

TypeScript
type TaskWithDue = Task & { due: string };

A TaskWithDue without a due date is an error:

TypeScript
const report: TaskWithDue = {
  id: 4,
  title: 'Send the report',
  status: 'todo',
};
Plain 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:

TypeScript
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:

TypeScript
interface TaskWithDue extends Task {
  due: string;
}

8. Functions

Take TaskWithDue and report out of task.ts, and add this below the tasks array:

TypeScript
function makeTask(
  title: string,
  notes?: string,
): Task {
  return {
    id: tasks.length + 1,
    title,
    status: 'todo',
    notes,
  };
}

Returning just the title instead is an error:

TypeScript
return title;
Plain Text
Type 'string' is not assignable to type 'Task'.

Add a function that doesn't return anything, then use them both:

TypeScript
function logTask(task: Task): void {
  console.log(`${task.id}. ${task.title}`);
}

tasks.push(makeTask('Pay rent'));
tasks.forEach(logTask);
Bash / Shell
node task.ts
Plain 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:

TypeScript
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:

TypeScript
function formatId(id: string | number) {
  return id.toUpperCase();
}
Plain Text
Property 'toUpperCase' does not exist on type 'string | number'.

Replace it with a version that checks first:

TypeScript
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:

Plain Text
(parameter) id: string
(parameter) id: number
Bash / Shell
node narrowing.ts
Plain Text
ABC #7

10. Data From Outside

Create data.ts. Here we trust the data with as:

TypeScript
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:

Plain Text
const data: any

But it crashes when you run it:

Bash / Shell
node data.ts
Plain Text
TypeError: Cannot read properties of undefined (reading 'toUpperCase')

Replace it with unknown, and using it without checking is an error:

TypeScript
import type { Task } from './task.ts';

const text = '{"id": 3, "name": "Call mom"}';
const data: unknown = JSON.parse(text);

console.log(data.title);
Plain Text
'data' is of type 'unknown'.

Check it first, and the error's gone:

TypeScript
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 / Shell
node data.ts
Plain Text
That is not a task

11. Generics

Create generics.ts. With any, TypeScript loses track of the type:

TypeScript
import { tasks } from './task.ts';

function first(items: any[]) {
  return items[0];
}

const firstTask = first(tasks);

Hover over firstTask:

Plain Text
const firstTask: any

Replace it with a generic, and the type follows the data through:

TypeScript
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:

Plain 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:

TypeScript
import type { Task } from './task.ts';

type NewTask = Omit<Task, 'id'>;

const draft: NewTask = {
  id: 5,
  title: 'Pay rent',
  status: 'todo',
};
Plain Text
Object literal may only specify known properties, and 'id' does not exist in type 'NewTask'.

Here's the finished file:

TypeScript
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:

Bash / Shell
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:

TypeScript
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:

JSON
"build": "tsc -b && vite build"

Create src/types.ts, which the video doesn't show:

TypeScript
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:

TypeScript
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:

TypeScript
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;
Plain Text
Property 'onToggle' is missing in type '{ tasks: Task[]; }' but required in type 'TaskListProps'.

Here's the finished src/App.tsx:

TypeScript
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:

TypeScript
const [tasks, setTasks] = useState([]);
Plain Text
const tasks: never[]
Type 'Task' is not assignable to type 'never'.

Hover over onChange to see the event type it wants:

Plain Text
(property) React.InputHTMLAttributes<HTMLInputElement>.onChange?: React.ChangeEventHandler<HTMLInputElement, HTMLInputElement> | undefined

RawImageDownload