1. Introduction to TypeScript
What is TypeScript?
TypeScript is a superset of JavaScript that adds static typing and other advanced features. It helps improve code safety, refactoring, and productivity.
Benefits of TypeScript
- Error Detection at Compile Time: Catch errors early, before runtime.
- Better Readability and Maintainability: Code becomes easier to understand and modify.
- Advanced Features: Support for interfaces, generics, and utility types.
- Compatibility with JavaScript: Enables gradual migration from JavaScript to TypeScript.
2. Installation and Configuration
Installing TypeScript
npm install -g typescript
Initializing a TypeScript Project
tsc --init
This generates a tsconfig.json
file, which allows you to manage your project’s TypeScript compiler options.
3. Basic Types
TypeScript has basic types to handle common data structures.
let isDone: boolean = true;
let age: number = 30;
let firstName: string = 'Alice';
let nothing: null = null;
let notDefined: undefined = undefined;
4. Arrays and Tuples
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ['Alice', 'Bob'];
let user: [string, number] = ['Alice', 30];
5. Enums
enum Role {
Admin,
User,
Guest,
}
let role: Role = Role.Admin;
6. any
and unknown
Types
any
: Disables TypeScript's type checking.unknown
: Forces a type check before usage.
let data: any = 42;
data = 'hello';
let value: unknown = 'test';
if (typeof value === 'string') {
console.log(value.toUpperCase());
}
7. Type Inference
TypeScript can infer types based on the values assigned.
let message = 'Hello'; // inferred as string
8. Union and Intersection Types
Union types allow multiple types, and intersection types combine them.
let result: string | number = 'ok';
result = 42;
type A = { id: number };
type B = { name: string };
type C = A & B;
const user: C = { id: 1, name: 'Alice' };
9. Literal Types
let direction: 'left' | 'right' | 'up' | 'down';
direction = 'left';
10. Functions and Return Types
Specify return types for functions to ensure consistency.
function greet(name: string): string {
return `Hello, ${name}`;
}
function log(message: string = 'Default'): void {
console.log(message);
}
11. void
and never
Types
void
: No return value.never
: A function that never successfully completes (e.g., throws an error).
function warnUser(): void {
console.warn('Warning!');
}
function fail(): never {
throw new Error('Something failed');
}
12. Interfaces
Interfaces define the structure of objects.
interface User {
id: number;
name: string;
}
const newUser: User = { id: 1, name: 'Alice' };
13. Type Aliases
Use type
to create a new type or combine types.
type ID = number | string;
let userId: ID = 123;
14. Optional Properties
interface Product {
id: number;
name?: string; // Optional
}
15. Readonly Properties
interface Car {
readonly id: number; // Readonly
brand: string;
}
16. Classes and Access Modifiers
Control property visibility with access modifiers.
class Person {
public name: string;
private age: number;
protected email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
}
17. The implements
Keyword
Implement an interface in a class.
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log('Woof');
}
}
18. Generics
Generics allow functions or classes to work with different types.
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>('Hello');
19. Generic Interfaces
interface Box<T> {
content: T;
}
const stringBox: Box<string> = { content: 'test' };
20. Type Assertions
Assert a variable to a specific type.
let someValue: unknown = 'this is a string';
let strLength: number = (someValue as string).length;
21. keyof
and typeof
Operators
Use keyof
to get all keys of a type, and typeof
to refer to the type of a variable.
interface User {
id: number;
name: string;
}
type UserKeys = keyof User; // "id" | "name"
22. Conditional Types
Use conditional types to define types based on other types.
type IsString<T> = T extends string ? true : false;
type Test = IsString<'hello'>; // true
23. Mapped Types
type ReadOnly<T> = {
readonly [P in keyof T]: T[P];
};
24. Utility Types: Partial
, Pick
, Omit
interface Task {
id: number;
name: string;
completed: boolean;
}
type PartialTask = Partial<Task>;
type PickTask = Pick<Task, 'id' | 'name'>;
type OmitTask = Omit<Task, 'completed'>;
25. Record
and Required
type UserRoles = Record<string, string>;
type FullTask = Required<Partial<Task>>;
26. Modules and Imports
TypeScript uses ES6 modules for organizing code.
// math.ts
export function add(x: number, y: number): number {
return x + y;
}
// main.ts
import { add } from './math';
27. Namespaces (Deprecated in Favor of Modules)
namespace MathUtils {
export function square(x: number): number {
return x * x;
}
}
let result = MathUtils.square(4);
28. Declaration Files
Declare types for non-TypeScript libraries.
// declare a global library
declare module 'my-library' {
export function greet(name: string): string;
}
29. tsconfig.json
Essentials
Common options in tsconfig.json
.
target
: ECMAScript versionstrict
: Enable strict type-checkingmodule
: Module system (e.g., CommonJS)esModuleInterop
: Compatibility with CommonJS
30. Using TypeScript with React
interface Props {
title: string;
}
const Header: React.FC<Props> = ({ title }) => <h1>{title}</h1>;