ts-helpers icon indicating copy to clipboard operation
ts-helpers copied to clipboard

variance modifier wrapper class

Open DetachHead opened this issue 2 years ago • 1 comments

like #162 but for the whole class

DetachHead avatar Jul 23 '22 12:07 DetachHead

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
})

DetachHead avatar Jul 24 '22 01:07 DetachHead