Skip to content

instanceof narrowing should use InstanceType #55241

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

Open
4 of 5 tasks
jrose-signal opened this issue Aug 2, 2023 · 0 comments
Open
4 of 5 tasks

instanceof narrowing should use InstanceType #55241

jrose-signal opened this issue Aug 2, 2023 · 0 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@jrose-signal
Copy link

jrose-signal commented Aug 2, 2023

Suggestion

πŸ” Search Terms

instanceof, narrow, generic, typeof

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code. (Stronger narrowing logic can result in additional errors being emitted.)
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

value instanceof SomeClass narrows value to SomeClass in subsequent flow. However, value instanceof someClass, where someClass is defined as someClass: T and T extends typeof BaseClass, only narrows value to BaseClass rather than InstanceType<T>.

See also #28936, though in this case I'm not referencing constructor at all.

πŸ“ƒ Motivating Example

If you want to downcast in a class hierarchy, you use instanceof. JavaScript's dynamism even allows you to dynamically pick the class to cast to. However, TypeScript doesn't understand that when the class is specified using generics, which prevents you from returning a corresponding instance type.

class Base {
  private readonly field: number;
  constructor(field: number) {
    this.field = field;
  }

  private downcastTo<T extends typeof Base>(subclass: T): InstanceType<T> {
    if (this instanceof subclass)
      return this; // error: Type 'this' is not assignable to type 'InstanceType<T>'
    throw new TypeError(`expected ${subclass.name}, got ${this.constructor.name}`);
  }

  static parse<T extends typeof Base>(this: T, input: string): InstanceType<T> {
    let result: Base;
    if (input == "Sub1") {
      result = new Sub1(1);
    } else if (input == "Sub2") {
      result = new Sub2(2);
    } else {
      throw new TypeError("invalid input");
    }
    return result.downcastTo(this);
  }
}

class Sub1 extends Base {
  // ...
}
class Sub2 extends Base {
  // ...
}

// Normal static method usage
const base: Base = Base.parse("sub1")
// Now also valid, with stronger checks
const sub1: Sub1 = Sub1.parse("sub1");

πŸ’» Use Cases

We are using this for a more realistic version of the example, parsing a serialized format into a type hierarchy. Some callers know that the serialized data should be a specific subclass, and that there should be an error if it doesn't match that subclass, and so it's convenient if the class you call parse on decides the type you get back.

Workarounds:

  • Have parse always return Base, downcast at call sites. Verbose: if (!(result instanceof Sub1)) throw new Error("…").
  • Use a type-predicate wrapper function for instanceof. This works but is unchecked by the compiler, and of course adds a small bit of overhead because the function won't be compiled away.
  • Use as InstanceType<T> to tell TypeScript we know what we're doing. Also works, also unchecked, but probably the workaround I'd recommend for now.
@jrose-signal jrose-signal changed the title instanceof narrowing on values should instanceof narrowing should use InstanceType Aug 2, 2023
@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature labels Aug 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants