Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add @FinalMethod #65

Open
AshGw opened this issue Apr 21, 2024 · 0 comments
Open

Add @FinalMethod #65

AshGw opened this issue Apr 21, 2024 · 0 comments

Comments

@AshGw
Copy link
Owner

AshGw commented Apr 21, 2024

New feature motivation

There should be a mechanism to mark classes and methods final, as in if a class is final, then one cannot subclass it, also, if a method is final, one should not be able to override it in the subclass.

There were many requests for the TypeScript team to implement this feature, check this, this and this, well since they haven't introduced it I doubt they ever will.

Now about final classes, the library already has a final class decorator and it works as intended, check it out here.

The problem is with a @finalMethod decorator implementation. I Haven't found a way to implement this feature yet.

New feature description

Something like

import { finalMethod } from 'ts-roids';
import type { NewType  } from 'ts-roids'; 

type Bar = NewType<'Bar', string>;

abstract class BaseFoo<T> {
  abstract someFoo(): T;
}

class Foo<T> extends BaseFoo<T> {
  foo: T;
  bar: Optional<string>;

  constructor(foo: T, bar?: string) {
    super();
    this.foo = foo;
    this.bar = bar ?? null;
  }
  override  someFoo(): T {
    return this.foo;
  }
  @finalMethod
  someBar(): Bar {
    return 'bar' as Bar
  }

}

class SubFoo extends Foo<string> {
  constructor(foo: string) {
    super(foo);
  }
  override someBar(): Bar { // This should not be possible 
    return 'not bar' as Bar
  }
}

// No problem with instantiation of `Foo`
const foo = new Foo<string>('foo');

// The line below SHOULD cause a TypeError upon instantiation: Cannot override the final method 'someBar'...
const sub = new SubFoo('subFoo');

/* 
  Now if instantiation is allowed because of a decorator limitation, then a TypeError should be 
  thrown when attempting to use the method somehow, like this: 
*/ 
const notBar = sub.someBar() // SHOULD throw: TypeError: Cannot override the final method 'someBar'...

New feature implementation

Well nothing worked yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant