Skip to content

Constrained generic class property has any type after instanceofΒ #60810

Closed as duplicate

Description

πŸ”Ž 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.

Activity

  1. jcalz commented on Dec 18, 2024

    @jcalz
    Contributor

    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?

  2. MartinJohns commented on Dec 18, 2024

    @MartinJohns
    Contributor

    Duplicate of #17473.

  3. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions