1

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?

1
  • 1
    No, there is no final in TypeScript; there's an old request languishing at ms/TS#1534 but it's not part of the language. There are various workarounds. Commented Oct 13 at 12:19

1 Answer 1

0

As a workaround you can use the following approach:

export class BaseService {
  public doSomething(): void {
    console.log("Base logic");
  }

  public doSomethingImportant(): void {
    console.log("Critical logic that must not be overridden");
  }
}

type NonOverridableBaseService = {
  doSomethingImportant?: never;
}

class MyService extends BaseService implements NonOverridableBaseService {
  public doSomethingImportant(): void {  // ❌ should cause a compile error
    console.log("Overridden critical logic");
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This causes a compile error even if you don't override doSomethingImportant.
You're right. Haven't checked this case. Seems, there is no opportunity to do it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.