TypeScript classes, this parameters and decorators
Classes are a JavaScript feature; TypeScript adds types and a set of compile-time checks on top of them. This hub covers only what TypeScript adds. For the runtime model of classes, fields, inheritance and #private members, read the JavaScript pages on classes, private fields and static blocks first; nothing on this page changes how they behave at run time, with one exception: decorators, which TypeScript compiles into real code.
The sections go from everyday class modeling (access modifiers, parameter properties, abstract classes, override) to the two features that trip people up in callbacks and frameworks: typing this, and decorators. Every sample is a complete ES module from an invented online shop, OrdersPortal, compiled with TypeScript 7.0.2 (tsc --strict --target es2025 --module nodenext) and run with Node.js 22. Save one as sample.ts next to a package.json containing {"type": "module"}, then run npx tsc --strict sample.ts and node sample.js.
Topics on this page
Section titled “Topics on this page”| Topic | Since | Use it when |
|---|---|---|
| Access modifiers and parameter properties | private 0.8; protected 1.3 |
You control who may use a member and want short constructors. |
| Abstract classes and interfaces | abstract 1.6 |
Several classes share code and a contract. |
| Override and property initialization | 2.7 and 4.3 | You want the compiler to catch broken inheritance and unset fields. |
| This parameters | TypeScript 2.0 | A function or method depends on what this is when it is called. |
| Decorators | Standard 5.0; legacy 1.5 | You attach reusable behavior to classes and members. |
Access modifiers and parameter properties
Section titled “Access modifiers and parameter properties”TypeScript has had public and private since its first release and added protected in 1.3. public is the default. private members are usable only inside the declaring class; protected members also in subclasses. readonly (TypeScript 2.0) allows assignment only in the declaration or the constructor.
These modifiers are compile-time checks only. The compiled JavaScript has ordinary properties, so a private field is visible to JSON.stringify, Object.keys and code that uses a bracket access such as cart["items"]. For privacy enforced at run time, use JavaScript’s #private fields, which TypeScript fully supports.
A parameter property is a constructor parameter with a modifier, such as constructor(private readonly customerId: string). It declares the property and assigns it in one step. It is one of the few TypeScript features that generates code, so it is rejected under erasableSyntaxOnly (TypeScript 5.8), the option for code that Node.js runs by stripping types; see Tooling and project structure.
interface CartLine { sku: string; quantity: number; unitPrice: number;}
class Cart { protected readonly lines: CartLine[] = []; #couponCode: string | undefined; // JavaScript private: hidden at run time too
constructor(public readonly customerId: string) {}
add(line: CartLine): this { this.lines.push(line); return this; }
applyCoupon(code: string): void { this.#couponCode = code; }
total(): number { const sum = this.lines.reduce((acc, l) => acc + l.quantity * l.unitPrice, 0); return this.#couponCode === "WELCOME10" ? sum * 0.9 : sum; }}
const cart = new Cart("C-1") .add({ sku: "SKU-RED-01", quantity: 2, unitPrice: 10 }) .add({ sku: "SKU-BLU-02", quantity: 1, unitPrice: 5 });cart.applyCoupon("WELCOME10");
console.log(cart.customerId, cart.total());console.log(Object.keys(cart)); // protected 'lines' is a normal property; #couponCode is not listedOutput:
C-1 22.5[ 'customerId', 'lines' ]Reading cart.lines outside the class fails with error TS2445: Property 'lines' is protected and only accessible within class 'Cart' and its subclasses.
Pitfalls:
privateis not a security boundary. Anything serialized or logged includes it. Use#privatefor secrets such as tokens.- Parameter properties hide declarations. In a long constructor they are easy to miss; some teams ban them for that reason and for compatibility with type stripping.
Abstract classes and interfaces
Section titled “Abstract classes and interfaces”Abstract classes arrived in TypeScript 1.6. An abstract class cannot be instantiated; it can declare abstract members that every concrete subclass must implement, alongside ordinary members with shared code. It is a good fit for a template method: the base class fixes the algorithm and the subclasses fill in the steps.
An interface, by contrast, is only a contract. A class states that it fulfills one with implements, which the compiler checks, but implements adds nothing to the class: no members, no types for its parameters. Because TypeScript is structural, a class satisfies an interface even without implements; writing it makes the compiler report a mismatch at the class instead of at the first place the class is used.
Use an interface for the contract callers depend on, and an abstract class only where subclasses genuinely share implementation.
interface PaymentProvider { readonly name: string; charge(amount: number): string;}
abstract class BasePaymentProvider implements PaymentProvider { abstract readonly name: string; protected abstract authorize(amount: number): boolean;
charge(amount: number): string { if (amount <= 0) return `${this.name}: invalid amount`; return this.authorize(amount) ? `${this.name}: charged ${amount.toFixed(2)}` : `${this.name}: declined`; }}
class CardProvider extends BasePaymentProvider { readonly name = "card"; protected authorize(amount: number): boolean { return amount < 1000; }}
class InvoiceProvider implements PaymentProvider { readonly name = "invoice"; charge(amount: number): string { return `${this.name}: invoice for ${amount.toFixed(2)} sent`; }}
const providers: PaymentProvider[] = [new CardProvider(), new InvoiceProvider()];for (const p of providers) { console.log(p.charge(59.9), "|", p.charge(1500));}Output:
card: charged 59.90 | card: declinedinvoice: invoice for 59.90 sent | invoice: invoice for 1500.00 sentWriting new BasePaymentProvider() fails with error TS2511: Cannot create an instance of an abstract class.
Pitfalls:
implementsdoes not type parameters. Inclass X implements PaymentProvider { charge(amount) { ... } },amountis implicitlyany(an error understrict); annotate it.- Deep abstract hierarchies are hard to change. Prefer composition (pass a
PaymentProviderin) over a third level of inheritance.
Override and property initialization
Section titled “Override and property initialization”Two strict-era checks make class code safer. strictPropertyInitialization (TypeScript 2.7, part of strict) requires every non-optional property to be assigned in its declaration or in the constructor. When a framework assigns it later, you can say so with a definite assignment assertion, name!: string, which switches the check off for that property.
The override keyword (TypeScript 4.3) marks a method or property that replaces one from the base class. With noImplicitOverride (not part of strict), every such member must say override. The payoff comes when the base class changes: if a base method is renamed or removed, every override of it becomes a compile error instead of silently turning into an unrelated new method that is never called.
class Notifier { protected sent: string[] = [];
send(customerId: string, message: string): void { this.sent.push(`${customerId}: ${message}`); }
history(): readonly string[] { return this.sent; }}
class QuietHoursNotifier extends Notifier { private readonly queue: string[] = []; private readonly startHour: number;
constructor(startHour: number, private readonly currentHour: () => number) { super(); this.startHour = startHour; // required by strictPropertyInitialization }
override send(customerId: string, message: string): void { if (this.currentHour() >= this.startHour) { this.queue.push(`${customerId}: ${message}`); return; } super.send(customerId, message); }
queued(): number { return this.queue.length; }}
let hour = 18;const notifier = new QuietHoursNotifier(22, () => hour);notifier.send("C-1", "Order ORD-1 shipped");hour = 23;notifier.send("C-2", "Order ORD-2 shipped");console.log(notifier.history(), notifier.queued());Output:
[ 'C-1: Order ORD-1 shipped' ] 1Declaring private readonly startHour: number; without the constructor assignment fails with error TS2564: Property 'startHour' has no initializer and is not definitely assigned in the constructor. Marking a method override when the base class has no such method fails with error TS4113: This member cannot have an 'override' modifier because it is not declared in the base class 'Notifier'.
Pitfalls:
!on a property is an unchecked promise. Use it only where a framework orinitmethod really assigns the value before use.- Turn on
noImplicitOverrideearly. Without it,overrideis optional and the protection only covers members someone remembered to mark.
This parameters
Section titled “This parameters”this parameters arrived in TypeScript 2.0. In JavaScript, the value of this inside a function depends on how the function is called, not where it is defined; a method passed as a callback loses its object. A this parameter is a fake first parameter, function total(this: Cart), that declares what this must be. It is erased from the output and callers do not pass it; the compiler checks every call site instead.
On methods, this: OrderTable makes the compiler reject calling a detached method (const fn = table.format; fn(order)). On standalone functions, it types this for code such as event handlers. The noImplicitThis option (part of strict) reports any use of this whose type would be any. The utility types ThisParameterType<F> and OmitThisParameter<F> read and remove the declared this type.
The usual fixes for a lost this are an arrow-function class field, which captures the instance, or .bind(instance).
interface Order { id: string; total: number;}
class OrderTable { constructor(private readonly orders: Order[], private readonly currency: string) {}
// Declares that this method needs an OrderTable as 'this'. format(this: OrderTable, order: Order): string { return `${order.id}: ${order.total.toFixed(2)} ${this.currency}`; }
// An arrow-function field captures the instance, so it is safe as a callback. formatSafe = (order: Order): string => `${order.id}: ${order.total.toFixed(2)} ${this.currency}`;
rows(): string[] { return this.orders.map(this.formatSafe); }}
function describeTotal(this: { currency: string }, total: number): string { return `${total} ${this.currency}`;}
const table = new OrderTable([{ id: "ORD-1", total: 40 }], "EUR");console.log(table.rows());console.log(table.format({ id: "ORD-2", total: 15 }));console.log(describeTotal.call({ currency: "USD" }, 99));
type FormatThis = ThisParameterType<typeof table.format>; // OrderTableconst bound: OmitThisParameter<typeof table.format> = table.format.bind(table);console.log(bound({ id: "ORD-3", total: 25 }));Output:
[ '1: 40.00 EUR' ]ORD-2: 15.00 EUR99 USDORD-3: 25.00 EURCalling a detached method is caught: const fn = table.format; fn(order); fails with error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'OrderTable'. So is assigning it to a callback type that declares this: void.
Pitfalls:
- Callbacks without a declared
thisare not checked.[order].map(table.format)compiles, because the callback type ofmapsays nothing aboutthis, and it throws at run time. Athisparameter protects direct calls, not every hand-off. - Arrow fields cost memory. Each instance gets its own function. That is fine for UI components; for thousands of objects, bind at the call site instead.
thisin a plain function isundefinedin modules. ES modules are strict mode, so an unbound function call hasthis === undefined, not the global object.
Decorators
Section titled “Decorators”TypeScript 5.0 implemented standard ECMAScript decorators, following the TC39 proposal at stage 3; TypeScript 1.5 had introduced an earlier, different design that is still available behind experimentalDecorators. A decorator is a function applied with @name to a class, method, accessor, field or accessor field (TypeScript 4.9). For a method, it receives the original method and a context object (ClassMethodDecoratorContext) with the member’s name, static/private flags and addInitializer, and may return a replacement method.
Unlike the rest of this page, decorators produce real runtime code. Because no runtime used here supports them natively, the compiler rewrites decorated classes into helper calls for the chosen target. Decorators suit cross-cutting behavior such as logging, timing, registration or validation, written once and applied declaratively.
Standard and legacy decorators are not compatible. Frameworks built on the legacy model, including Angular and NestJS, still require "experimentalDecorators": true, which changes the decorator signature (target, propertyKey, descriptor) and enables parameter decorators and emitDecoratorMetadata, which the standard model does not have. TypeScript 5.2 added decorator metadata (context.metadata) for the standard model.
function logged(label: string) { return function <This, Args extends unknown[], Return>( method: (this: This, ...args: Args) => Return, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>, ) { const name = String(context.name); return function (this: This, ...args: Args): Return { console.log(`[${label}] ${name}(${args.join(", ")})`); return method.call(this, ...args); }; };}
const registry = new Map<string, new () => unknown>();
function handler(kind: string) { return function <T extends new () => unknown>(value: T, context: ClassDecoratorContext<T>): void { context.addInitializer(() => registry.set(kind, value)); };}
@handler("card")class CardRefunds { @logged("refunds") refund(orderId: string, amount: number): string { return `refunded ${amount} on ${orderId}`; }}
console.log([...registry.keys()]);console.log(new CardRefunds().refund("ORD-1042", 19.99));Output:
[ 'card' ][refunds] refund(ORD-1042, 19.99)refunded 19.99 on ORD-1042Pitfalls:
- Check which model your framework uses. Mixing them produces confusing signature errors; with
experimentalDecoratorson, the sample above fails with errors such aserror TS1241: Unable to resolve signature of method decorator when called as an expression. - Type the decorator generically. A decorator typed with
anyhides mismatches between the decorated method and the wrapper. - No parameter decorators in the standard model. Dependency injection by parameter decorator (
@Inject()on a constructor parameter) still needs the legacy option.
Choosing between them
Section titled “Choosing between them”- For privacy that matters at run time, use
#private; for API hygiene within a codebase,privateandprotectedare enough. - For a contract, use an interface; add an abstract class only when subclasses share real code.
- Turn on
noImplicitOverridein new projects, and keepstrictPropertyInitializationon. - For methods used as callbacks, use arrow-function fields or
bind, and declarethisparameters on functions that depend onthis. - Use standard decorators in new code; keep
experimentalDecoratorsonly where a framework requires it.
Interview questions
Section titled “Interview questions”What is the difference between private and #private?
private is a TypeScript compile-time check; the compiled property is an ordinary, enumerable, accessible property. #private is a JavaScript private field enforced by the runtime: it is invisible to Object.keys, JSON.stringify and outside code, and accessing it from outside is a syntax error.
What does implements do at run time?
Nothing. It asks the compiler to check that the class satisfies the interface and to report mismatches at the class declaration. It does not add members or types to the class, and the interface does not exist at run time.
Why use noImplicitOverride?
It requires override on every member that replaces a base-class member. If the base member is later renamed or removed, the override becomes an error, instead of the subclass member silently becoming a new method that the base class never calls.
Why does orders.map(table.format) lose this, and how do you fix it?
map calls the function without a receiver, so this is undefined in a module. A this: OrderTable parameter catches direct detached calls, but not this hand-off, because the callback type of map does not declare this. Fix it with an arrow-function field, table.format.bind(table) or an inline arrow (o) => table.format(o).
What changed with decorators in TypeScript 5.0?
TypeScript implemented the standard TC39 decorators, which have a different signature ((value, context)) from the legacy experimental decorators ((target, key, descriptor)), support accessor fields and addInitializer, and do not support parameter decorators or emitDecoratorMetadata. The legacy model is still available with experimentalDecorators for frameworks that depend on it.
Senior scenario: OrdersPortal’s service classes leak customer tokens into logs, and code reviews keep finding methods that silently stopped overriding after a base-class rename. What would you change?
Move secrets to #private fields so serialization and logging cannot see them, and add a toJSON that returns only safe fields for the classes that are logged. Turn on noImplicitOverride and fix the resulting errors, which will also reveal the orphaned methods. Consider whether the inheritance is needed at all; replacing a deep hierarchy with injected collaborators often removes the renaming risk entirely.
Related pages
Section titled “Related pages”- Objects, interfaces and classes: the beginner tutorial for classes.
- Generics and functions: generic classes and functions.
- Utility types:
ConstructorParametersandInstanceType. - Tooling and project structure:
strict,erasableSyntaxOnlyand other options mentioned here. - Private fields in JavaScript and private methods.
Official references
Section titled “Official references”- TypeScript Handbook: Classes
- TypeScript Handbook: Decorators (legacy experimentalDecorators model)
- TypeScript 2.0 release notes: this parameters and readonly
- TypeScript 4.3 release notes: override and noImplicitOverride
- TypeScript 5.0 release notes: decorators
- TypeScript 5.2 release notes: decorator metadata
- TC39 decorators proposal