Codectionary / Developer documentation / TypeScript

Typed Classes

TypeScript enhances JavaScript classes with typed properties, constructor parameters, and method signatures. Class fields must either be initialized or explicitly typed, and TypeScript checks that constructor assignments match declared property types, catching mismatches before runtime.

Syntax

class Name {
  property: type;
  constructor(param: type) { }
}

Examples

Typed Properties and Constructor

Declaring class fields with explicit types, initialized via the constructor.

class User {
  id: number;
  name: string;
  email: string;

  constructor(id: number, name: string, email: string) {
    this.id = id;
    this.name = name;
    this.email = email;
  }

  describe(): string {
    return `${this.name} (${this.email})`;
  }
}

const user = new User(1, "Alice", "alice@example.com");
console.log(user.describe());

Parameter Properties Shorthand

A concise way to declare and assign class properties directly in the constructor signature.

class Product {
  constructor(
    public id: number,
    public name: string,
    private price: number
  ) {
    // TypeScript automatically creates and assigns these three properties -
    // no need to repeat "this.id = id" etc manually
  }

  getPrice(): number {
    return this.price;
  }
}

const product = new Product(1, "Laptop", 999);
console.log(product.name);      // accessible - public
// console.log(product.price);   // Error - private

Best practices

  • Use parameter properties (public/private directly in the constructor signature) to reduce repetitive boilerplate for simple classes
  • Type every class property explicitly, or initialize it with a value TypeScript can infer from - uninitialized untyped properties default to any implicitly, weakening safety
  • Keep constructors focused on initialization - complex setup logic is often clearer in a separate method or factory function
  • Use readonly on properties that should be set once in the constructor and never modified afterward

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading