TypeScript Reference ยท Classes, Enums and Decorators
TypeScript class methods
Reference for TypeScript class methods: parameter and return types, overloads, optional parameters, async and generator methods, and how this is bound.
A method is a function declared inside a class body. It lives on the prototype, is shared by all instances, and receives the instance as this when you call it as obj.method(). TypeScript checks its parameters and return type like any function, and gives this the type of the class.
Methods may be async, generators, overloaded, static, abstract, or have access modifiers. The one subtle point is this: it depends on how the method is called, not where it is defined.
class Greeter { constructor(private name: string) {} greet(greeting = "Hello"): string { return `${greeting}, ${this.name}`; } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
class C { [modifiers] [async] [*] name[?]<T>(params): ReturnType { body } [modifiers] name(params): ReturnType; // overload signature }
| Part | Description |
|---|---|
| Modifiers | public, protected, private, static, abstract, override. |
async / * |
Make the method asynchronous (returns Promise<T>) or a generator. |
? |
Declares an optional method, mostly used when implementing optional interface members. |
<T> |
Method-level type parameters, separate from class-level ones. |
| Return type | Inferred if omitted; write it explicitly on public API methods. |
Edge cases:
- A
thisparameter (method(this: Foo)) is erased at runtime and only constrains how the method may be called. - Returning
thisgives a polymorphic this type, useful for chaining. - A method that is only declared as an overload signature without an implementation causes an error.
Usage notes
- Methods are defined once on the prototype, so detached calls such as
setTimeout(obj.method)losethis. Fix it with an arrow wrapper,.bind(obj), or an arrow-function field. - Arrow-function fields allocate one closure per instance and cannot be overridden with
super.method(); choose them only where the binding matters. - With
strictBindCallApply,call,applyandbindare type-checked against the method signature. - Method parameters are checked bivariantly when you compare a method type to another, but properties declared as function types are checked strictly under
strictFunctionTypes. This difference matters for subclass overrides and interfaces. - Use
overridetogether withnoImplicitOverrideto catch typos in overriding methods.