Type compatibility breaks when class 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?

3

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

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật