-
Notifications
You must be signed in to change notification settings - Fork 12.8k
querySelector and querySelectorAll should support generics for "string" selectors #12568
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
querySelector and querySelectorAll should support generics for "string" selectors #12568
Comments
Actually I think this is supposed to work. The purpose of the interface is to enable it to return the correct types as mapped. The problem is that key is not being inferred as a literal. If you use this definition it works interface NodeSelector {
querySelector<K extends string & keyof ElementTagNameMap>(selectors: K): ElementTagNameMap[K] | null;
querySelector(selectors: string): Element | null;
querySelectorAll<K extends string & keyof ElementListTagNameMap>(selectors: K): ElementListTagNameMap[K];
querySelectorAll(selectors: string): NodeListOf<Element>;
} |
@aluanhaddad the use case I described, i.e. union types for (possibly) mixed type selection, is not covered by the latest |
Sorry I missread the original comment. At the time these declarations were not returning the specific types even for non-unions |
PRs welcomed. You can find more information about contributing lib.d.ts fixes at https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md#contributing-libdts-fixes. |
@YuichiNukiyama thanks for tackling this so quickly! @mhegazy thanks for the link, seems I am too late this time around... |
What is the difference between using generic and type assertion?
|
@FranklinWhale IMHO |
Is there any update on whether the PR will be accepted? |
TypeScript Version: 2.2.0-dev.20161129
Code
As of the TS version stated above the
NodeSelector
in lib.es6.d.ts interface is defined as:Expected behavior:
It should be possible to use a generic to control the return type of the general string-based selection methods, rather than being returned a fixed return type of
Element
. I.e. assume one uses a classmy-svg-shape
which one exclusively applies to either an SVGrect
orcircle
.There should be method signatures to control the return type at the developer's discretion, i.e.
These would obviously fall back to the current behavior, if used without specifying a type, but could be used as, e.g.
Actual behavior:
Return type is fixed to
Element
EDIT: Fixed copy-paste typo in application example. Inserted
.my-svg-shape
as selector string.The text was updated successfully, but these errors were encountered: