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

Return type of convert requires casting when used in TypeScript #14

Closed
oozcitak opened this issue Mar 27, 2020 · 3 comments
Closed

Return type of convert requires casting when used in TypeScript #14

oozcitak opened this issue Mar 27, 2020 · 3 comments
Assignees
Labels
bug Something isn't working

Comments

@oozcitak
Copy link
Owner

From: oozcitak/xmlbuilder-js#147 (comment)

@oozcitak oozcitak added the bug Something isn't working label Mar 27, 2020
@oozcitak oozcitak self-assigned this Mar 27, 2020
@leafac
Copy link
Contributor

leafac commented Mar 30, 2020

@oozcitak: Thanks for working on this.

I tried the following:

xmlbuilder2.convert(`<a>b</a>`, { format: "object" }).a;

And the TypeScript compiler complains that:

error TS2339: Property 'a' does not exist on type 'XMLSerializedAsObject | XMLSerializedAsObjectArray'.
  Property 'a' does not exist on type 'XMLSerializedAsObjectArray'.

That’s because the return type of convert() is declared to be either an object or an array. But I think the actual returned value is always an object and never an array. For example, the following fails:

xmlbuilder2.convert(`<a>b</a><c>d</c>`, { format: "object" });
// Error: The operation would yield an incorrect node tree. Document already has a document element node. Node is c.

As it stands, I still have to cast the return of convert() with as any.

Am I doing something wrong? Or could the declared return type of convert() be only XMLSerializedAsObject?

@oozcitak
Copy link
Owner Author

No you are right, it can never return an array. I'll look into it.

@leafac
Copy link
Contributor

leafac commented Mar 30, 2020

After thinking some more about it, the truth is that even if convert() returned an object, every property of that object could be an object or an array, so the benefit is limited. It may better to leave it as it is. Either you’re safe and always check for arrays, or you use a type assertion like I mentioned (as any).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants