Search code examples
typescript

Type compatibility breaks when class<T> has a property that's a function referencing T


I have a generic type class and I want to be able to save an instance of this class into a WeakMap that I declare with WeakMap<MyClass<unknown>, ...> because it will hold instances of different generic versions of MyClass.

Now, the class instances have a property (not a method on the prototype), which I assign in the constructor, and the property is a function which accepts an argument that is the same type as the generic one of the instance. And that seems to result in an error when I try to save it in WeakMap. But the weird thing is that if I make a version of the class that instead of declaring this function as a property, declares it as a method on the prototype, then it works even if I override this in the constructor in the same way as in the original version.

Here's an example:

const FooData = new WeakMap<Foo<unknown>, number>();
class Foo<K> {
  someFuncProp: (k: K) => K; // this breaks it, why?

  constructor() {
    this.someFuncProp = (k: K) => k;
    FooData.set(this, 1); // this errors because of someFuncProp
  }
}

const BarData = new WeakMap<Bar<unknown>, number>();
class Bar<K> {
  constructor() {
    this.someFuncProp = (k: K) => k; // that doesn't break it
    BarData.set(this, 1); // this is fine
  }

  // whatever, overridden
  someFuncProp(k: K) {
    return k;
  }
}
Argument of type 'this' is not assignable to parameter of type 'Foo<unknown>'.
  Type 'Foo<K>' is not assignable to type 'Foo<unknown>'.
    Types of property 'someFuncProp' are incompatible.
      Type '(k: K) => K' is not assignable to type '(k: unknown) => unknown'.
        Types of parameters 'k' and 'k' are incompatible.
          Type 'unknown' is not assignable to type 'K'.
            'K' could be instantiated with an arbitrary type which could be unrelated to 'unknown'.

Playground

What is happening?


Solution

  • If you have a class Foo<T> with arbitrary members that depend in different ways on T, then it is almost certainly the case that Foo<T> is invariant in T, meaning that even if A extends B, neither Foo<A> extends Foo<B> nor Foo<B> extends Foo<A>. So in general you can't assign Foo<T> to Foo<unknown> for arbitrary Foo. For that to work you'd need Foo<T> to be covariant in T. See Difference between Variance, Covariance, Contravariance, Bivariance and Invariance in TypeScript

    This is a consequence of substitutability. If X extends Y it means you should be able to substitute a value of type X for a value of type Y without causing problems. If Foo<T> is defined like

    class Foo<T> {
      someFuncProp: (t: T) => T;
      constructor() {
        this.someFuncProp = (t: T) => t;
      }
    }
    

    And then we make a value of type Foo<string>, say via subclassing:

    class Baz extends Foo<string> {
      constructor() {
        super()
        this.someFuncProp = (t: string) => t.toUpperCase();
      }
    }
    

    Then the assignment you're trying to make with FooData.set(this, 1) is the same as assigning a Baz to a Foo<unknown>:

    const foo: Foo<unknown> = new Baz(); // this is an error in TS
    

    That's an error, assuming you have the --strictFunctionTypes compiler option enabled. It's an error because, if it were allowed, you could call this:

    foo.someFuncProp(123); // RUNTIME ERROR! t.toUpperCase is not a function
    

    where foo.someFuncProp() accepts any argument whatsoever (since all values are of type unknown), but Baz's someFuncProp is only expecting string arguments, and blows up if you give it something like 123.

    So that's why FooData.set(this) fails. Foo<T> is invariant in T, so you cannot assign Foo<T> to Foo<unknown> unless T is unknown.


    On the other hand, the reason why BarData.set(this) succeeds is because TypeScript is intentionally unsafe about method parameters. It checks method parameters bivariantly. So then Bar<T> is apparently covariant in T and you can assign a Bar<string> to Bar<unknown>.

    This is just as unsafe as Foo<T> though, it's just that TypeScript has decided that most people don't actually trip over this sort of error with methods in practice, or not enough to justify breaking a bunch of stuff.

    See the TypeScript FAQ entry "Why Method Bivariance?".


    Also, in practice, you really don't care about this sort of substitutability issue for the keys of a WeakMap, because these keys aren't directly observable. You can't get a key out of a WeakMap so you can't call its someFuncProp() method at all. Maybe WeakMap should just be bivariant in its key type, but it's not.

    I'd say that in cases where you don't need to worry about variance, you should use the intentionally unsound any type instead of unknown:

    const FooData = new WeakMap<Foo<any>, number>();
    
    class Foo<K> {
      someFuncProp: (k: K) => K; 
    
      constructor() {
        this.someFuncProp = (k: K) => k;
        FooData.set(this, 1); // okay
      }
    }
    

    Yes, someone might balk at using any, but there really isn't a reason to avoid it for WeakMap keys, and at least you're being explicit about the bivariance instead of just accidentally using it with methods.

    Playground link to code