Skip to content
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

Can generics be added to methods that return types that are extended or any? #356

Open
lordheart opened this issue May 19, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@lordheart
Copy link

lordheart commented May 19, 2022

For instance the method byId on

  • "sap/ui/core/mvc/Controller"
  • "sap/ui/core/mvc/View"
  • "sap/ui/core/UIComponent"

Etc. all return UI5Element, but this usually means that accessing say the SetEnabled method on a sap/m/Select throws a typescript error that the method is not found.

const selectElement = this.getView().byId(anIDforASelectElement);
selectElement.setEnabled(enabled); // error here

If the byId method was generic it could be called like this

const selectElement = this.getView().byId<Select>(anIDforASelectElement);
selectElement.setEnabled(enabled); 

Like that type completion would then work and no errors would be thrown.

The generic declaration can even be added in a manner that makes it optional to add the generic type for current code using the types returned UI5Element.

The current definition
byId(sId: string ): UI5Element;
would just need to be changed to
byId<T extends UI5Element = UI5Element>(sId: string): T;

Would this be possible and wanted or is casting (using as Select) the preferred approach? If not then possibly the returns of type any could be changed to unknown to force a typecheck.

I extended "sap/ui/base/Event" in a similiar manner to allow myself to pass in the Parameter types so that event.getParameter also has type completion. But I need to learn more about how events work to figure out how many generic parameters I would need to have all it's methods return typed objects instead of any.

Edit: this is using the sap/ui5-types-esm

@lordheart lordheart changed the title Can generics be added to methods that return Objects that are extended? Can generics be added to methods that return types that are extended or any? May 19, 2022
@codeworrior
Copy link
Member

This was already discussed in #16 and also in one of our Sample Apps (SAP-samples/ui5-cap-event-app#5 (comment)).

Microsoft's own dtslint rules recommend not to use generics like this (they call it "disguised type assertion").
That's one of the reasons why we did not yet invest here (e.g. the tool chain issues mentioned in #16 still exist).

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

No branches or pull requests

3 participants