Lesson 3: TypeScript Fundamentals for JavaScript Developers
Goal
Learn TypeScript fundamentals to transition from JavaScript. By the end of this lesson, students will confidently use TypeScript features in their apps.
1. Learning Objectives
By the end of this lesson, students will:
- Understand TypeScript basics: types, interfaces, generics, and enums.
- Learn how TypeScript integrates into React (
tsxfiles). - Apply TypeScript concepts in practical examples.
2. Why Use TypeScript?
TypeScript solves common JavaScript challenges:
- Type Errors: Catch errors at compile time rather than runtime.
- Code Readability: Enforces clear interfaces and structures.
- Intellisense: Provides better autocompletion and tooling support.
- Refactoring: Makes it easier to refactor large apps.
3. TypeScript Basics
3.1. Type Annotations
In TypeScript, you specify variable types using a colon (:).
Example:
let task: string = "Buy groceries";
let completed: boolean = false;
let duration: number = 2;
console.log(`Task: ${task}, Duration: ${duration} hours`);Key Types:
| Type | Description | Example |
|---|---|---|
string |
Text values | "Complete homework" |
number |
Numeric values | 42 |
boolean |
True/False values | true / false |
any |
Disables type-checking | let x: any = "Hi"; |
array |
Arrays of a specific type | number[] |
void |
Functions returning no value | function log(): void |
null/undefined |
Null and undefined values | let x: null |
3.2. Interfaces
Interfaces define the shape of an object.
Example:
interface TodoItem {
id: number;
title: string;
completed: boolean;
}
const myTask: TodoItem = {
id: 1,
title: "Learn TypeScript",
completed: false,
};
console.log(myTask);Benefits:
- Provides a blueprint for object structure.
- Ensures consistency.
- Improves maintainability.
3.3. Functions with TypeScript
TypeScript adds type safety to function parameters and return values.
Example: Function Parameters and Return Types
function addTask(title: string, completed: boolean): string {
return `Task: ${title}, Completed: ${completed}`;
}
console.log(addTask("Walk the dog", false));3.4. Union Types and Optional Fields
Union Types allow multiple types for a variable.
Optional Fields are marked with ?.
Example:
interface Task {
title: string;
duration?: number; // Optional field
}
function printTask(task: string | number): void {
console.log(`Task: ${task}`);
}
printTask("Code review"); // Works
printTask(2); // Works3.5. Enums
Enums represent a set of named constants.
Example:
enum TaskStatus {
NotStarted,
InProgress,
Completed,
}
let currentStatus: TaskStatus = TaskStatus.InProgress;
console.log(currentStatus); // Outputs 1 (index in the enum)4. TypeScript in React
React uses TSX files to integrate TypeScript. Components now have type safety for props and state.
4.1. Adding TypeScript to a React Component
Install TypeScript in React:
If you haven't already initialized TypeScript:
npx create-react-app todolist --template typescript4.2. React Props with TypeScript
Example: TodoItem Component with TypeScript Props
import React from "react";
interface TodoItemProps {
title: string;
completed: boolean;
}
const TodoItem: React.FC<TodoItemProps> = ({ title, completed }) => {
return (
<div>
<h3>{title}</h3>
<p>Status: {completed ? "Completed" : "Not Completed"}</p>
</div>
);
};
export default TodoItem;4.3. React State with TypeScript
State uses useState with type annotations.
Example: Managing Todo State
import React, { useState } from "react";
interface Todo {
id: number;
title: string;
completed: boolean;
}
const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([
{ id: 1, title: "Learn React", completed: false },
{ id: 2, title: "Learn TypeScript", completed: true },
]);
return (
<div>
<h1>Todo List</h1>
{todos.map((todo) => (
<div key={todo.id}>
<h3>{todo.title}</h3>
<p>{todo.completed ? "Done" : "Pending"}</p>
</div>
))}
</div>
);
};
export default App;5. Homework Assignment
-
Create a TypeScript interface for a
Taskobject with:id(number)title(string)completed(boolean)
- Write a TypeScript function that accepts the
Taskobject and returns a message like:
"Task: Learn TypeScript | Status: Completed" - Create a basic React Component (
TaskItem.tsx) that takes theTaskobject as props and displays thetitleandstatus.
Next Lesson Preview: Lesson 4
In Lesson 4, we will:
- Deep dive into TypeScript with React and TSX in larger applications.
- Start building reusable components for the TodoList app.
