RicoSuter/NSwag

Generated TypeScript constructors don't properly handle nested types

Open

#1,218 创建于 2018年3月11日

在 GitHub 查看
 (0 评论) (3 反应) (0 负责人)C# (6,291 star) (1,189 fork)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.

贡献者指南

Generated TypeScript constructors don't properly handle nested types · RicoSuter/NSwag#1218 | Good First Issue