In the context of using an extends
or implements
clause, you cannot directly employ an expression. However, a workaround is to create a type alias and utilize that instead. Interestingly, you can even assign the same name as the anonymous class (const
) since they reside in separate spaces (value space vs type space).
const AnonymousClass = class {
static staticField = 0;
instanceField = 0;
}
let a: typeof AnonymousClass;
type AnonymousClass = typeof AnonymousClass
interface I extends AnonymousClass {
}
let foo: I;
foo.instanceField // invalid
foo.staticField // valid
The above code snippet extends the static interface of the class. If your intention is to extend the instance interface instead, you can achieve this by using an additional InstanceType
conditional type:
const AnonymousClass = class {
static staticField = 0;
instanceField = 0;
}
let a: typeof AnonymousClass;
type AnonymousClass = InstanceType<typeof AnonymousClass>
interface I extends AnonymousClass {
}
let foo: I;
foo.instanceField // valid
foo.staticField // invalid
Access Playground link here