2

Does anyone know how to get the current class in an abstract-generic-class | how to reference the current class like a type "CurrentClass" and not just the abstract class?

reason: i'm writing a small library, that should "infer" the current class without doing "as CurrentClass"

abstract class Super {
  public static create(args: keyof CurrentClass) {}
}

class CurrentClass extends Super {}

// to prevent
CurrentClass.create({} as CurrentClass);

i searched everywhere, but couldnt find an answer to this, so is it even possible in typescript?


this question would solve it, but not for static functions

Update: it seems that this is the issue i was looking for

1 Answer 1

1

The usual workaround is to add a type parameter to infer the target from the call:

abstract class Super {
  s = ""
  public static create<T>(this:new (...a: any[]) => T, args: keyof T) {}
}

class CurrentClass extends Super {
  c = ""
}

// to prevent
CurrentClass.create("c"); // ok
CurrentClass.create("s"); // ok

play

Sign up to request clarification or add additional context in comments.

6 Comments

but this workaround wouldnt give me the keys(/type infomation) from the abstract Super class, right?
@hasezoey sure it would, that comes from inheritance .. in the example I added keys from both Super and CurentClass. If you don't want keys from Super you can use Exclude
i meant like in the create function i wouldnt have the types of super, because i cant see an "extends" or assignment there
@hasezoey There are multiple variations of the solution depending on your needs.You could do create<T extends Super> if you need access to instance members of super. You will not have access to the statics of Super although if we complicate the type a bit more you can gain access to them. Let me know if you have a concrete issue you are having trouble with.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.