Swagger-codegen: [Question] Can Swagger generate custom generic types?

Created on 16 May 2018  路  9Comments  路  Source: swagger-api/swagger-codegen

Assume we have API return model in C#

public class ApiResult<T>
{
  public T Result;
  public bool Success;
}

and returning ApiResult<string> object instance to client

so we have swagger generated model

ApiResult[String] {
  result (string, optional),
  success (boolean, optional)
}

which is incorrectly converted to typescript class using https://swagger.io/swagger-codegen/

'use strict';
import * as models from './models';
export interface ApiResultString {
    result?: string;
    success?: boolean;
}

Is it possible to generate output models with generics same as in input models?

Most helpful comment

i'm not so familiar with typescript, but if you guys conclude that this is the best practice, we can implement it.

All 9 comments

Bump

i'm not so familiar with typescript, but if you guys conclude that this is the best practice, we can implement it.

I agree with the opening post.
Generally ApiResult is a generic wrapper from the real payload from the rest backend.

At this moment if you have n APIs that all wraps n different objects, you end having ApiResultObjectApi1... ApiResultObjectApi2... ApiResultObjectApiN in the generated code.
Several useless repetition that serves a "difficult" to use api.service.ts

Since typescript supports generics, it would be ideal to generate the typescript interfaces as generics as well. The code that use those could be more generic and the models would be DRY and smaller.

A little more thinking into this and i just realized that there is an indecision case.

Suppose a c# mode like this

public class ApiResult<T>
{
  public T Result;
  public bool Success;
  public string message;
}

and an api returning ApiResult<string> object instance to client

so we would have swagger generated model

ApiResult[String] {
  result (string, optional),
  success (boolean, optional)
  message (string, optional)
}

how the generator's template should behave?
It doesn't know which of the strings are from the generics.

Maybe a typescript-angular generate's option like enableGenerics (default: false) should be better. so you can enable it only iff you're sure of the api's model.

Yes, the spec needs to be updated to handle this case. Otherwise, a generator would need a minimum of two types being used in a generic result before it could decide which properties are generic and which properties are stationary.

Hi, is there any progress on supporting generics in TypeScript yet? Thanx!

I have a same problem.

I wish to use this feature too

Same

Was this page helpful?
0 / 5 - 0 ratings