ts-helpers
ts-helpers copied to clipboard
variance modifier wrapper class
like #162 but for the whole class
failed attempt:
export const safeVariance = <Type extends AnyConstructor>(
type: Type,
): SafeVarianceConstructor<Type> =>
type as SafeVarianceConstructor<Type>
// this doesn't work because it needs to know how many generics the constructor takes.
// intersecting it with `Type` in an attempt to fix that doesn't work because that just makes it return the original instance type and not the SafeVariance one
type SafeVarianceConstructor<Type extends AnyConstructor> = Type & (new (...args: ConstructorParameters<Type>) => SafeVariance<InstanceType<Type>>)
test('safeVariance', () => {
class A<T> extends safeVariance(
class<T> {
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- testing safeVariance
foo(_value: T) {
return 1
}
},
)<T> {
}
class B<T> extends safeVariance(
class<T> extends A<T> {
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- testing safeVariance
override foo(value: T) {
return super.foo(value)
}
},
)<T> {
}
const a = new B<number>()
const b: B<unknown> = a // no error but there should be
})