RicoSuter/NSwag

Generated TypeScript constructors don't properly handle nested types

Open

#1,218 opened on 2018年3月11日

GitHub で見る
 (0 comments) (3 reactions) (0 assignees)C# (6,291 stars) (1,189 forks)batch import
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.

コントリビューターガイド