Skip to content

querySelector return type could be more specific for single-element selectors #8114

Description

The return types for querySelector and querySelectorAll (in the lib.es6.d.ts) could provide more specific return type information when the selector a single element selector for a known element type.

I.e., right now the types are

interface NodeSelector {
    querySelector(selectors: string): Element;
    querySelectorAll(selectors: string): NodeListOf<Element>;
}

But it could be expanded in the style of getElementsByTagName:

interface NodeSelector {
    querySelector(selectors: "a"): HTMLAnchorElement;
    querySelector(selectors: "abbr"): HTMLPhraseElement;
    ...
    querySelector(selectors: string): Element;
}

It's a minor convenience, but does eliminate the occasional typecast.

Activity

  1. DanielRosenwasser commented on Apr 17, 2016

    @DanielRosenwasser
    Member

    I don't think this is totally unreasonable. Mohamed Hegazy (@mhegazy) Zhengbo Li (@zhengbli) any thoughts on this?

  2. added this to the milestone on Apr 18, 2016
  3. mhegazy commented on Apr 18, 2016

    @mhegazy
    Contributor

    PRs welcomed. here is some instructions on submitting lib.d.ts PRs: https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md#contributing-libdts-fixes

  4. modified the milestones: TypeScript 2.0, on Jun 10, 2016
  5. thw0rted commented on Jul 31, 2017

    @thw0rted

    I'm a vanilla Javascript user but I benefit from this in VS Intellisense. So, I don't know TS well enough to answer my question: would it be possible to implement this with regex or partial-string matching, such that querySelector("a.someClass") also returns a more specific class (i.e. HTMLAnchorElement)? It's the same operating theory, right? I don't think it's possible for querySelector to return a non-Anchor for the selector example I gave, is it?

  6. kitsonk commented on Jul 31, 2017

    @kitsonk
    Contributor

    Pattern matching of overloads is #165 and it being applied to querySelector() would be different than this closed issue, which has been resolved.

  7. thw0rted commented on Jul 31, 2017

    @thw0rted

    OK, I think that fills in the blanks of the Typescript syntax I was missing. I asked on StackOverflow about good ways to handle this in the short term, and I'm happy enough with the answer, but returning a more specific type (eventually) would make for better code.

  8. locked and limited conversation to collaborators on Jun 19, 2018
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

    FixedA PR has been merged for this issueHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions