Skip to main content

Typing class methods

1. How to type method parameters

Typing method parameters in a class is no different from regular functions.

javascript
class User { greet(name: string, age: number): void { console.log(`Hello, ${name}! You are ${age} years old.`); } }

Here:

  • name is a parameter of type string,
  • age is a parameter of type number,
  • void means the method returns nothing.

An example with optional and default parameters

javascript
class Logger { log(message: string, prefix: string = "INFO", userId?: number) { console.log(`[${prefix}] ${message}`, userId ?? ""); } } const logger = new Logger(); logger.log("Started"); // [INFO] Started logger.log("Error", "ERROR", 101); // [ERROR] Error 101
  • prefix = "INFO" is a default value;
  • userId?: number is an optional parameter.

An example with rest parameters

javascript
class MathUtils { sum(...numbers: number[]): number { return numbers.reduce((a, b) => a + b, 0); } } const utils = new MathUtils(); console.log(utils.sum(1, 2, 3, 4)); // 10

Rest parameters (...numbers: number[]) are also typed as an array.


An example with an object as a parameter

javascript
class UserService { createUser({ name, age }: { name: string; age: number }): void { console.log(`Created user: ${name}, ${age}`); } }

You can move the type into an interface:

javascript
interface CreateUserDto { name: string; age: number; } class UserService { createUser(user: CreateUserDto): void { console.log(`Created user: ${user.name}`); } }

An example with a generic method parameter

javascript
class DataService { save<T>(data: T): T { console.log("Saved:", data); return data; } } const service = new DataService(); service.save<string>("text"); service.save({ id: 1, name: "Tim" });

T is a generic that makes the method universal: it accepts and returns type T.


2. How to type a method's return value

After the parameter list, : type is specified, which describes what the method returns.


Example 1: An explicit return value

javascript
class Calculator { add(a: number, b: number): number { return a + b; } }

The method returns a number, so : number is used.


Example 2: The return value is an object

javascript
class UserFactory { createUser(name: string, age: number): { name: string; age: number } { return { name, age }; } }

You can describe the return type right at the declaration, or via an interface:

javascript
interface User { name: string; age: number; } class UserFactory { createUser(name: string, age: number): User { return { name, age }; } }

Example 3: The return value is void

If the method returns nothing (it only performs actions):

javascript
class Logger { log(message: string): void { console.log(message); } }

void means: "returns nothing" (equivalent to a function with no return or with return;).


Example 4: The return value is a Promise

javascript
class Api { async fetchUser(id: number): Promise<{ id: number; name: string }> { return { id, name: "Tim" }; } }

For async methods, the type is always Promise<ReturnType>.


Example 5: The return value is this

Sometimes a method returns the object itself (for chaining):

javascript
class Builder { private value = ""; append(str: string): this { this.value += str; return this; } get(): string { return this.value; } } const b = new Builder(); console.log(b.append("Hi").append(" there!").get()); // "Hi there!"

this means "the current instance type of the class", and it is useful for fluent APIs (method chains).


Example 6: A return value from a union type

javascript
class Parser { parse(value: string): number | null { const n = Number(value); return isNaN(n) ? null : n; } }

The method can return several types (number or null).


3. Summary: method syntax with types

javascript
class Example { methodName(param1: Type1, param2: Type2): ReturnType { // method body } }

SUMMARY TABLE

What is typedExampleDescription
A parametergreet(name: string)the argument's type
Multiple parametersadd(a: number, b: number)each parameter has its own type
An optional parameterlog(msg?: string)can be omitted
A default parameterlog(msg = "ok")a default value
Returning voiddoSomething(): voidreturns nothing
Returning Promisefetch(): Promise<User>an asynchronous result
Returning thisappend(s: string): thisenables chaining
A genericsave<T>(data: T): Ta universal type

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.