Skip to content

Constrained generic class property has any type after instanceof #60810

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
OliverJAsh opened this issue Dec 18, 2024 · 2 comments
Closed

Constrained generic class property has any type after instanceof #60810

OliverJAsh opened this issue Dec 18, 2024 · 2 comments

Comments

@OliverJAsh
Copy link
Contributor

πŸ”Ž Search Terms

  • Type parameters
  • Class
  • instanceof
  • any

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about generics.

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/MYGwhgzhAECyCeBRATsg9sgPAFWgUwA8AXPAOwBMYIjkBLUgcwD5oBvAKGmgAcBXAIxC1g0IgC5o2ANydowNKWrJewIhgAU4yQEo2srkQAWtCADoi0ALyiZXAL7sH7cnlBhkeOQur5UGCQgo6FhK9MzQAD7QvKQA1qRoAO6kMuy0AGbQ6nh+yND01GCkwHhomYG5uhxcOcHmttAA9I1cXAB6APyyzfgE3K4k5BKhjN0tYKq8YCASRfDQgDLkjkA

πŸ’» Code

class MyError<T extends string> {
  public t: T;
  constructor(t: T) {
    this.t = t;
  }
}

declare const error: MyError<string> | unknown;

if (error instanceof MyError) {
  error.t;
  //    ^?
  // expected: string
  // actual: any ❌
}

πŸ™ Actual behavior

See above.

πŸ™‚ Expected behavior

See above.

Additional information about the issue

Potentially related?: #17253. Although, this one seems to be for anonymous classes, which is not the case here.

@jcalz
Copy link
Contributor

jcalz commented Dec 18, 2024

Your MyClass<string> | unknown confused me for a minute into thinking you were asking for something else (i.e., that MyClass<X> | unknown should be narrowed to MyClass<X> if you use instanceof, but that's not possible because unknown absorbs everything). Maybe you can just change it to unknown, since that's the same thing and there's no implication of narrowing to a union member?

Is the idea that since MyClass<T> is covariant in T, that the constraint should be used instead of any when narrowing via instanceof? And if it were contravariant you'd expect never, and if it were invariant or otherwise problematic then any would be fine?

@MartinJohns
Copy link
Contributor

Duplicate of #17473.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants