RicoSuter/NSwag
在 GitHub 查看Generated TypeScript constructors don't properly handle nested types
Open
#1,218 建立於 2018年3月11日
help wantedproject: NJsonSchemaproject: NJsonSchema.CodeGeneration.TypeScripttype: bug
描述
The TypeScript constructors NSwag generates are as follows:
constructor(data?: IFoo) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
However, this doesn't work correctly for nested types. Consider:
class Foo {
bar: Bar;
}
class Bar {
name: string;
age: number;
}
let a = new Foo({bar: {name: 'Fido', age: 5}});
The constructor doesn't complain, but the Bar inside of a is still an IBar rather than a real Bar. This is a problem because then when you call a generated controller method using a, it will crash inside toJSON because it's trying to call toJSON on a plain old javascript object, and not the expected Bar.
I think to fix this, the generated constructor needs to explicitly assign each property rather than iterating through them. It will then be able to call constructors for non-primitive types.