user6096764 :
I need to make analogue of Java class literal with generics in TypeScript.
This is my Class class:
class Class<T> {
public getName(): string {
return ...;
}
}
And this is my attempt to create class literal.
declare global {
interface Object {
class<T extends object>(this: T): Class<T>;//LINE X
}
}
For example, for class Foo
I want to get literal this way: Foo.class()
. However, at LINE X I have some mistake because it returns Class<typeof Foo>
instead of Class<Foo>
. How to fix it?
Titian Cernicova-Dragomir :
Since this is meant to be called on classes, you will need a restriction on T
to ensure that the method only shows up on classes. This can be done using a constructor signature (new (...a: any[])=> any
)
Since T
is a class type and you want the instance type you can use the predefined conditional type InstanceType
to get the instance type from the class type:
declare global {
interface Object {
class<T extends new (...a: any[])=> any>(this:T): Class<InstanceType<T>>;
}
}