nashwaan / xml-js

Converter utility between XML text and Javascript object / JSON text.
MIT License
1.27k stars 180 forks source link

Overload type for xml2js #125

Open erezwanderman opened 4 years ago

erezwanderman commented 4 years ago

The function xml2js is currently declared as returning "Element | ElementCompact". This means I can't assign it the result to a variable of type Element even if I specify {compact: false}.

const x: Element = convert.xml2js('<a></a>', { compact: false});
// Error    TS2322  (TS) Type 'Element | ElementCompact' is not assignable to type 'Element'.
  Type 'Element' is missing the following properties from type 'Element': assignedSlot, classList, className, clientHeight, and 122 more.

I suggest changing the declaration to something like this:

  xml2js(xml: string): Element;
  xml2js(xml: string, options?: { compact: true } & Options.XML2JS): ElementCompact;
  xml2js(xml: string, options?: { compact: false } & Options.XML2JS): Element;
  xml2js(xml: string, options?: Omit<Options.XML2JS, 'compact'>): Element;
  xml2js(xml: string, options?: Options.XML2JS): Element | ElementCompact;

So that typescript can detect the type when possible.

joshgrift commented 3 years ago

Coming across this issue as well. +1