I'm using NSwag to create a TypeScript client for an existing service.
It generates TypeScript that looks like this (example below is a simplified version to highlight the issue):
export interface IModelBase { }
export class ModelBase implements IModelBase {
constructor(data?: IModelBase) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
}
export interface IDerived {
name?: string | undefined;
}
export class Derived extends ModelBase implements IDerived {
name?: string | undefined;
constructor(data?: IDerived) {
super(data);
}
}
When I attempt to instantiate this class with:
let d = new Derived({name: "Bob"});
alert(d.name);// Shows undefined
This appears to be happening because when TypeScript transpiles this to JavaScript, it generates something like this:
class ModelBase {
constructor(data) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property)) this[property] = data[property];
}
}
}
}
class Derived extends ModelBase {
constructor(data) {
super(data);
this.name = void 0;//!!!Why is this here?
}
}
I'm guessing that TypeScript can't "see" the assignment of the name field because it's hidden in the ModelBase constructor in the for(property in data)
loop so it's trying to ensure that the field is initialized to undefined. Unfortunately this occurs after the call to super(...) which presumably did assign a value
When I put the example above into https://www.typescriptlang.org/play I haven't been able to find any combination of settings that causes this, so where is it coming from?
I am using this typescript within a create-react-app I'm not sure how to figure out if this codegen is occurring in TypeScript or somewhere else.
Typescript Version 5.2.2
I would expect to be able to create an initialize a TypeScript class defined by NSwag as recommended in: https://github.com/RicoSuter/NSwag/discussions/4044