TypeScript (TS)

TypeScript (TS) is a superset of JavaScript that adds static typing and other features to help catch errors early, improve code maintainability, and enable better tooling (like autocomplete). It compiles to plain JavaScript.

Here are the most important concepts in TypeScript, each with a brief explanation and a small example.

1. Basic Types TypeScript provides primitive types to explicitly define variable types.

typescript

let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
let nothing: null = null;
let undefinedValue: undefined = undefined;

// Arrays
let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ["a", "b"];

2. Type InferenceTypeScript infers types when not explicitly annotated, reducing boilerplate.

typescript

let city = "New York";  // Inferred as string
city = 123;             // Error: Type 'number' is not assignable to 'string'

3. Any, Unknown, Never, Void

  • any: Disables type checking (avoid when possible).
  • unknown: Safer alternative; requires narrowing before use.
  • void: For functions returning nothing.
  • never: For values that never occur (e.g., endless loops).

typescript

let flexible: any = 5;
flexible = "hello";     // OK

let safe: unknown = 10;
if (typeof safe === "number") {
  console.log(safe + 5);  // OK after narrowing
}

function throwError(): never {
  throw new Error("Oops");
}

function log(): void {
  console.log("No return");
}

4. Union and Intersection Types

  • Union (|): Value can be one of several types.
  • Intersection (&): Combines multiple types.

typescript

let id: string | number = "abc";
id = 123;  // OK

type Admin = { name: string; privileges: string[] };
type Guest = { name: string; readonly: boolean };
type ElevatedUser = Admin & Guest;  // Has all properties

5. Type Aliases and InterfacesDefine custom types. Interfaces are more extensible (can be merged).

typescript

type Point = { x: number; y: number };  // Type alias

interface Shape {
  color: string;
}
interface Circle extends Shape {
  radius: number;
}

let circle: Circle = { color: "red", radius: 10 };

6. Functions and OverloadsTyped parameters, returns, and optional/default params. Overloads allow multiple signatures.

typescript

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
  return a + b;
}

add(1, 2);      // number
add("hello", "world");  // string

7. GenericsCreate reusable components that work with multiple types.

typescript

function identity<T>(arg: T): T {
  return arg;
}

let output = identity<string>("hello");  // T is string
let num = identity(42);                 // Inferred as number

interface Box<T> {
  value: T;
}
let stringBox: Box<string> = { value: "test" };

8. EnumsNamed constants for sets of values.

typescript

enum Direction {
  Up = 1,
  Down,
  Left,
  Right
}

let move: Direction = Direction.Up;  // 1

9. TuplesFixed-length arrays with typed positions.

typescript

let pair: [string, number] = ["age", 30];
pair[0] = "name";  // OK if string
pair[2] = true;   // Error: Tuple type has only 2 elements

10. Type Narrowing and GuardsNarrow types using checks (typeof, instanceof, in, custom guards).

typescript

function printLength(x: string | number) {
  if (typeof x === "string") {
    console.log(x.length);  // x narrowed to string
  } else {
    console.log(x.toFixed());  // x narrowed to number
  }
}

function isString(val: any): val is string {  // Type predicate
  return typeof val === "string";
}

11. Classes and OOP FeaturesSupport for classes with access modifiers, inheritance, abstract classes.

typescript

class Animal {
  protected name: string;  // Accessible in subclasses
  constructor(name: string) {
    this.name = name;
  }
  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance}m`);
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof!");
  }
}

const dog = new Dog("Buddy");
dog.move(10);
dog.bark();

12. Utility TypesBuilt-in types for transforming others (e.g., Partial, Required, Pick, Omit, Readonly).

typescript

interface User {
  id: number;
  name: string;
  email?: string;
}

type PartialUser = Partial<User>;  // All properties optional
type RequiredUser = Required<User>;  // All required
type NameOnly = Pick<User, "name">;
type NoId = Omit<User, "id">;
type Frozen = Readonly<User>;  // Can't modify properties

13. Advanced Type Manipulation

  • Conditional Types: Type logic like ternaries.
  • Mapped Types: Transform object keys.
  • Template Literal Types: String patterns.

typescript

type IsString<T> = T extends string ? "yes" : "no";
type Test = IsString<"hello">;  // "yes"

type Flags<T> = { [K in keyof T]: boolean };  // Map to boolean properties

type EventName = `on${"click" | "hover"}`;  // "onclick" | "onhover"

These cover the core of TypeScript. For the latest features (as of 2026), check the official docs for improvements like better inference and stricter checks, but the fundamentals remain the same. Practice by adding types to existing JavaScript code!

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *