Typing class methods
1. How to type method parameters
Typing method parameters in a class is no different from regular functions.
class User {
greet(name: string, age: number): void {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
}Here:
nameis a parameter of typestring,ageis a parameter of typenumber,voidmeans the method returns nothing.
An example with optional and default parameters
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 101prefix = "INFO"is a default value;userId?: numberis an optional parameter.
An example with rest parameters
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)); // 10Rest parameters (
...numbers: number[]) are also typed as an array.
An example with an object as a parameter
class UserService {
createUser({ name, age }: { name: string; age: number }): void {
console.log(`Created user: ${name}, ${age}`);
}
}You can move the type into an interface:
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
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
class Calculator {
add(a: number, b: number): number {
return a + b;
}
}The method returns a number, so
: numberis used.
Example 2: The return value is an object
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:
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):
class Logger {
log(message: string): void {
console.log(message);
}
}
voidmeans: "returns nothing" (equivalent to a function with noreturnor withreturn;).
Example 4: The return value is a Promise
class Api {
async fetchUser(id: number): Promise<{ id: number; name: string }> {
return { id, name: "Tim" };
}
}For
asyncmethods, the type is alwaysPromise<ReturnType>.
Example 5: The return value is this
Sometimes a method returns the object itself (for chaining):
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
class Parser {
parse(value: string): number | null {
const n = Number(value);
return isNaN(n) ? null : n;
}
}The method can return several types (
numberornull).
3. Summary: method syntax with types
class Example {
methodName(param1: Type1, param2: Type2): ReturnType {
// method body
}
}SUMMARY TABLE
| What is typed | Example | Description |
|---|---|---|
| A parameter | greet(name: string) | the argument's type |
| Multiple parameters | add(a: number, b: number) | each parameter has its own type |
| An optional parameter | log(msg?: string) | can be omitted |
| A default parameter | log(msg = "ok") | a default value |
Returning void | doSomething(): void | returns nothing |
Returning Promise | fetch(): Promise<User> | an asynchronous result |
Returning this | append(s: string): this | enables chaining |
| A generic | save<T>(data: T): T | a universal type |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.