I'm using TypeScript and have a class that is exported so its methods can be imported and used elsewhere. However, I’d like to make only certain methods non-overridable when someone extends the class — not all of them.
For example:
export class BaseService {
public doSomething(): void {
console.log("Base logic");
}
public doSomethingImportant(): void {
console.log("Critical logic that must not be overridden");
}
}
I want the following to be allowed:
import { BaseService } from "./BaseService";
new BaseService().doSomethingImportant();
But I want TypeScript to forbid overriding only doSomethingImportant():
class MyService extends BaseService {
public doSomethingImportant(): void { // ❌ should cause a compile error
console.log("Overridden critical logic");
}
}
Is there any way to mark only some methods as final (non-overridable), while keeping the class and its methods importable and usable externally?
finalin TypeScript; there's an old request languishing at ms/TS#1534 but it's not part of the language. There are various workarounds.