NaturalIntelligence / fast-xml-parser

Validate XML, Parse XML and Build XML rapidly without C/C++ based libraries and no callback.
https://naturalintelligence.github.io/fast-xml-parser/
MIT License
2.45k stars 296 forks source link

fix(types): make `build` and `parse` generic #594

Closed sarahdayan closed 10 months ago

sarahdayan commented 1 year ago

Purpose / Goal

This PR improves typing for build and parse by making both functions generic.

It also fixes the return type of build, which should be string.

parse

// Before
const result = xml.parse(data); // `result` is `any`

// After
type ExpectedObject = {
  title: string;
  description: string;
};

const result = xml.parse<ExpectedObject>(data); // `result` is `ExpectedObject`

build

// Before
const xml = builder.build(obj); // `xml` is `any`

// After
const xml = builder.build(obj); // `xml` is `string`

Type

Please mention the type of PR

amitguptagwl commented 1 year ago

Can you please explain me your changes for parse function? What exactly we're expecting

sarahdayan commented 1 year ago

@amitguptagwl This is only a type change. parse used to return any, forcing you to cast it. Now you can provide a generic type to maintain type-safety, which is usually preferrable as many linters frown upon type casting.

amitguptagwl commented 1 year ago

What I can understand here is to define the return type of parser to ExpectedObject with properties title and description which is not true for parser. Hence, I'm confusd what exactly you mean with the type you defined.

equipatuequipo commented 10 months ago

In the example they gave the type ExpectedObject has the properties title and description but in a real world use that type have the properties that you expect the parsed XML to have. For example for this XML:

<person>
     <name>John</name>
     <surname>Doe</surname>
</person>

the corresponding Typescript type would be:

type Person = {
    name: string;
    surname: string;
}

and you would use it like:

const result = xml.parse<Person>(data);

This would make the result variable have the type Person instead of any which is much better in terms of type safety. You can read more about generics here.