RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.67k stars 1.23k forks source link

convertConstructorInterfaceData set to true does not convert properly #4735

Open swfaust opened 7 months ago

swfaust commented 7 months ago

We are generating a TS client and I think I found a bug (or at least I don't understand and it's not working how I would think it should).

So if you go into the file and turn on the convertConstructorInterfaceData switch it will try to put converters in the classes to convert generic objects to the right classes. As an example here is one of our class constructors generated with the property set to true:

constructor(data?: ICreateJobRequest) { super(data); if (data) { this.options = data.options && !(<any>data.options).toJSON ? new JobOptions(data.options) : <JobOptions>this.options; } }

The issue I see is in the assignment of this.options. As I understand it the intended logic goes something like this. Check if the options property is set. If so check if the object has a toJSON function (which would indicate it's a full class object). If it does NOT have this property then assume it's a generic object and construct an options object with it, creating a full proper class object. If it DOES have that method it's a full object already so just cast it and use it.

That is all good but look at the last part of the ternary operator. Instead of casting data.options to JobOptions it's casting this.options. this.options is what we are trying to set and since this is the constructor of course it will be undefined. So in effect this constructor will make the options property undefined if you pass a full object for the options property on the interface. Further, since the interface wants a full object that is almost certainly what you are going to get, so this effectively makes this constructor non-functional when data is passed.

I may be missing something so please point out if I am, but this seems like a bug.