'Custom utility types (generic types) for classes `IsClass` of TypeScript
I am trying to create a generic type to make sure the first parameter to be a class. However, the factory function parameter cannot be replaced by a generic type.
The following upper parts were my attempts. The last part were a working example that directly write the extends ... which worked.
Why does it works inside a function, but not works as a generic type IsClass?
class A {
constructor() {
}
}
class B {}
class C extends B {}
// ERRORS:
type IsClass<T extends new (...args: any) => InstanceType<T>> = T
type IsClass2<T> = T extends new (...args: any) => InstanceType<T>? T: never
type X = IsClass<A>
type Y = IsClass2<A>
function someFactoryError<T>(clx: IsClass<T>) {
return new clx()
}
someFactoryError(A)
function someFactoryError2<T>(clx: IsClass2<T>) {
return new clx()
}
someFactoryError2(A)
// WORKS:
function someFactoryWorks<T extends new (...args: any) => InstanceType<T>>(clx: T) {
return new clx()
}
const a0 = someFactoryWorks(A)
const b0 = someFactoryWorks(B)
Related:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
