Here’s a comprehensive list of TypeScript topics, ranging from basic to advanced, along with brief explanations and examples:
1. Basic Types
- Primitive Types:
string
,number
,boolean
,null
,undefined
,void
. - Example:
let isDone: boolean = false; let decimal: number = 6; let color: string = "blue";
2. Type Annotations
- Explicitly declaring the type of a variable or function.
- Example:
function add(a: number, b: number): number { return a + b; }
3. Interfaces
- Defining the shape of an object.
- Example:
interface Person { name: string; age: number; } const user: Person = { name: "John", age: 30 };
4. Functions
- Optional and Default Parameters:
function buildName(firstName: string, lastName?: string): string { return lastName ? `${firstName} ${lastName}` : firstName; }
- Rest Parameters:
function buildName(firstName: string, ...restOfName: string[]): string { return `${firstName} ${restOfName.join(" ")}`; }
5. Union and Intersection Types
- Union: A value that can be one of several types.
- Intersection: Combining multiple types into one.
- Example:
function padLeft(value: string, padding: number | string) { if (typeof padding === "number") { return Array(padding + 1).join(" ") + value; } if (typeof padding === "string") { return padding + value; } throw new Error(`Expected string or number, got '${padding}'.`); }
6. Type Aliases
- Creating a new name for a type.
- Example:
type StringOrNumber = string | number; function logValue(value: StringOrNumber) { console.log(value); }
7. Enums
- A way to define a set of named constants.
- Example:
enum Color { Red, Green, Blue } let c: Color = Color.Green;
8. Generics
- Writing functions and classes that work with multiple types.
- Example:
function identity<T>(arg: T): T { return arg; } let output = identity<string>("myString");
9. Classes
- Object-oriented features like inheritance, access modifiers, and interfaces.
- Example:
class Animal { private name: string; constructor(name: string) { this.name = name; } public move(distance: number) { console.log(`${this.name} moved ${distance}m.`); } } class Dog extends Animal { bark() { console.log("Woof! Woof!"); } } const dog = new Dog("Buddy"); dog.bark(); dog.move(10);
10. Modules
- Splitting code into reusable modules.
- Example:
// math.ts export function add(x: number, y: number): number { return x + y; } // main.ts import { add } from "./math"; console.log(add(5, 3));
11. Namespaces
- Organizing code into logical groups.
- Example:
namespace Geometry { export class Circle { constructor(public radius: number) {} area() { return Math.PI * this.radius ** 2; } } } const circle = new Geometry.Circle(5); console.log(circle.area());
12. Decorators
- Special kinds of declarations that can be attached to classes, methods, properties, or parameters.
- Example:
function sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype); } @sealed class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return `Hello, ${this.greeting}`; } }
13. Advanced Types
- Mapped Types: Creating types by transforming properties.
- Example:
type Readonly<T> = { readonly [P in keyof T]: T[P]; }; interface Person { name: string; age: number; } const readonlyPerson: Readonly<Person> = { name: "John", age: 30 };
- Conditional Types: Types that depend on a condition.
- Example:
type MessageOf<T> = T extends { message: unknown } ? T["message"] : never; interface Email { message: string; } type EmailMessageContents = MessageOf<Email>; // string
14. Type Guards
- Using runtime checks to narrow types.
- Example:
function isNumber(x: any): x is number { return typeof x === "number"; } function doSomething(x: number | string) { if (isNumber(x)) { console.log(x.toFixed(2)); } else { console.log(x.toUpperCase()); } }
15. Utility Types
- Predefined types to transform types.
- Example:
interface Person { name: string; age: number; location?: string; } type PartialPerson = Partial<Person>; // All properties are optional type ReadonlyPerson = Readonly<Person>; // All properties are readonly
16. Type Inference
- Types are inferred based on the assigned value.
- Example:
let x = 3; // inferred as number
17. Index Signatures
- Defining types for properties of an object with dynamic keys.
- Example:
interface StringArray { [index: number]: string; } let myArray: StringArray; myArray = ["Bob", "Fred"];
18. Discriminated Unions
- Unions of types with a common, literal field.
- Example:
interface Square { kind: "square"; size: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type Shape = Square | Rectangle; function area(shape: Shape) { switch (shape.kind) { case "square": return shape.size * shape.size; case "rectangle": return shape.width * shape.height; } }
19. Advanced Generics
- Generic Constraints: Restricting types that can be used with generics.
- Example:
function loggingIdentity<T extends { length: number }>(arg: T): T { console.log(arg.length); return arg; } loggingIdentity({ length: 10, value: 3 });
20. Type Compatibility
- Understanding how different types relate to each other.
- Example:
interface Named { name: string; } class Person { name: string; } let p: Named; p = new Person(); // OK