Closed
Description
TypeScript Version: 3.7.3
Search Terms: abstract class, generic, infer
Code
type InstanceViaNew<T> = T extends { new (...args: never[]): infer R } ? R : never
type InstanceViaProto<T> = T extends { prototype: infer R } ? R : never
function classFactory1<T>() {
class CS {
x!: T
}
return CS
}
const CSS = classFactory1<string>()
type CS1 = InstanceViaNew<typeof CSS>["x"] // ok, string
type CS2 = InstanceViaProto<typeof CSS>["x"] // not ok, any :(
function classFactory2<T>() {
abstract class ACS {
x!: T
}
return ACS
}
const ACS = classFactory2<string>()
type AC1 = InstanceViaNew<typeof ACS>["x"] // not ok, never (because abstract classes have no new) :(
type AC2 = InstanceViaProto<typeof ACS>["x"] // not ok, any :(
Expected behavior:
There should be a way to make abstract classes keep the generic information and use it.
Actual behavior:
There's no way to make abstract classes keep the generic information and use it (unless they are type-casted to non abstract classes by adding to them a fake constructor).
Related Issues: #26829