Nswag: Error TS2449: Class 'BaseClient' used before its declaration

Created on 26 Nov 2018  路  23Comments  路  Source: RicoSuter/NSwag

Versions >=12.0.0.0, the class BaseClient is generated at the end of the file and TypeScript throw error "Error TS2449: Class 'BaseClient' used before its declaration".

NJsonSchema.CodeGeneration.TypeScript question

Most helpful comment

12.2.5 was working fine for me. But, updating to 12.3.0 which was released 5 hours ago gives me the error TS2449: Class 'Foo' used before its declaration.

It seems the ordering of how the model classes are written in the output .ts file is not taking into account the inheritance between them.

All 23 comments

I'm also facing this issue.

Generated using the NSwag toolchain v12.0.1.0 (NJsonSchema v9.12.3.0 (Newtonsoft.Json v11.0.0.0)) (http://NSwag.org)

image

image

image

<Target Name="ClientBuildAndBundle" AfterTargets="Build" Condition="$(SkipCustomization)!='true'">
    <Copy SourceFiles="@(ReferencePath)" DestinationFolder="$(OutDir)References" />
    <Exec Command="$(NSwagExe_Core21) run $(SpaRoot)nswag.json /variables:Configuration=$(Configuration)" />
    <RemoveDir Directories="$(OutDir)References" Condition="$(SkipCustomization)!='true'" />
</Target>

```json
"codeGenerators": {
"swaggerToTypeScriptClient": {
"className": "{controller}Client",
"moduleName": "",
"namespace": "",
"typeScriptVersion": 2.7,
"template": "Fetch",
"promiseType": "Promise",
"httpClass": "Http",
"injectionTokenType": "OpaqueToken",
"dateTimeType": "Date",
"nullValue": "Undefined",
"generateClientClasses": true,
"generateClientInterfaces": true,
"generateOptionalParameters": false,
"wrapDtoExceptions": false,
"wrapResponses": false,
"generateResponseClasses": false,
"responseClass": "SwaggerResponse",
"useTransformOptionsMethod": false,
"useTransformResultMethod": false,
"generateDtoTypes": true,
"operationGenerationMode": "MultipleClientsFromOperationId",
"markOptionalProperties": true,
"generateCloneMethod": false,
"typeStyle": "Interface",
"extensionCode": "src/api/client.extensions.ts",
"clientBaseClass": "BaseClient",
"generateDefaultValues": true,
"excludedTypeNames": [],
"handleReferences": false,
"generateConstructorInterface": true,
"convertConstructorInterfaceData": false,
"importRequiredTypes": true,
"useGetBaseUrlMethod": true,
"baseUrlTokenName": "API_BASE_URL",
"queryNullValue": "",
"output": "src/api/controllers.ts"
}
}


```javascript
// ...
function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any {
    if(result !== null && result !== undefined)
        throw result;
    else
        throw new SwaggerException(message, status, response, headers, null);
}

export class BaseClient {

    public getBaseUrl = (path?: string) => {
        return getBaseUrl();
    }
}
// ...

This setup worked before with:

Generated using the NSwag toolchain v11.20.1.0 (NJsonSchema v9.11.0.0 (Newtonsoft.Json v9.0.0.0))

What is the content of client.extensions.ts?

````javascript
export class BaseClient {

public getBaseUrl = (path?: string) => {
    return getBaseUrl();
}

}

export function getBaseUrl(): string {
const a = document.createElement("a");
a.href = (document.getElementsByTagName('base')[0] || {}).href;
const isIE = (window.navigator.userAgent.indexOf("MSIE ") > 0
|| window.navigator.userAgent.indexOf('Trident/') > 0);
// IE11 and lower need a '/' in the begining of pathname
const prefix = (isIE && a.pathname !== "" ? "/" : "");
return prefix + a.pathname.substr(0, a.pathname.lastIndexOf('/'));
}

What is the content of client.extensions.ts?

image

export class BaseClient {
    // Este m茅todo se ejecuta cada vez que realizamos una petici贸n al servicio web
    protected transformOptions(options: any) {
        return Promise.resolve(options);
    }

    // M茅todo que pinta la petici贸n y respuesta
    protected transformResult(url: string, response: HttpResponseBase, processor: (response: HttpResponseBase) => any): Observable<any> {
        return processor(response);
    }
}

Looks good to me (v12.0.1):

image

Output:

image

XD.

I created a new project with same settings the old project (In case it was broken) and it remains.

Project Nswag:
https://www.dropbox.com/s/rup20qufmu6qwx6/Config-Nswag-Problem-With-BaseClient.nswag?dl=1

This my settings:
image

Output:
image

If i select my test.ts file it works:

image

Maybe you have \r\n instead of \n in there?

test.zip

image

Nswag is sensitive from version >=12.0.0.0

Solution:
Use BLANKS instead of TABS (--->)

Thanks you help @RSuter

This is not good. Will check it

I'm still having this problem with the latest v12.0.3.0

The fix is not released yet.

@Wezea do you think the fix https://github.com/RSuter/NJsonSchema/commit/a2fd2158785d956b1e010aea58a64884e24178c2 will solve your problem too?

No, I do only have blanks and CR, LF in my file, no tabs. So this fix won't do something on my side.

What is your problem then? Can you post the extensions ts file?

These are the controller.ts and client.extension.ts. The build chain settings are described here

The problem is still that the BaseClient is insert after the Client.

api.zip

I had accidentally added my base class to the extendedClasses property which resulted in this behavior... Doesn't appear you've done that, but thought I'd mention it for anyone else who might come along with this issue. Makes sense since extended classes need to be declared after the generated ones.

12.2.5 was working fine for me. But, updating to 12.3.0 which was released 5 hours ago gives me the error TS2449: Class 'Foo' used before its declaration.

It seems the ordering of how the model classes are written in the output .ts file is not taking into account the inheritance between them.

12.2.5 was working fine for me. But, updating to 12.3.0 which was released 5 hours ago gives me the error TS2449: Class 'Foo' used before its declaration.

It seems the ordering of how the model classes are written in the output .ts file is not taking into account the inheritance between them.

The same happened to me just now

12.2.5 was working fine for me. But, updating to 12.3.0 which was released 5 hours ago gives me the error TS2449: Class 'Foo' used before its declaration.
It seems the ordering of how the model classes are written in the output .ts file is not taking into account the inheritance between them.

The same happened to me just now

Here as well

Will fix this soon

Was this page helpful?
0 / 5 - 0 ratings