typescript - 当参数的类型是泛型时,是否可以在 typescript 中为参数设置默认值?

标签 typescript generics casting

我正在编写通用方法以便在不同的前端应用程序中使用它们,我的想法是能够调用函数 .postAsync<CustomModel>('www.mysite.com',..., CustomModel); ,预期的响应是一个 CustomModel 对象。

我希望能够为第二个参数设置默认值,这样默认情况下该值将是不同的模型,并且可以在需要时覆盖。

如何为 Constructable<T> 类型的参数设置默认值? Constructable接口(interface)的意思是

interface Constructable<T> { new(params : any): T ;}

我已经尝试设置一个接受参数的接口(interface)的默认值并将参数设置为不同的类型,但我总是得到错误 Type Constructable<CustomModel> is not assignable to type Constructable<T> .我还在 CustomModel 通用方法中设置了 T 的默认类型,然后尝试了这个并得到了同样的错误。

interface Constructable<T> { new(params : any): T ;}


export default class WebapiBase {

    static async postAsync<T = CustomModel>(
        uri: string,
        body: object,
        headers: CustomHeaders = new CustomHeaders(),
        // This is the part giving errors
        model: Constructable<T> = <Constructable<CustomModel>>,): Promise<T> {
        return this.requestAsync<T>(model, HTTP_METHOD.POST, uri, headers, body);
    }

    private static async requestAsync<T>(
        model: Constructable<T>,
        method: HTTP_METHOD,
        uri: string,
        headers: CustomHeaders,
        body?: object): Promise<T> {
        const url = new URL(uri, window.location.origin);
        const request = this.buildRequest(url, method, headers, body);
        const bodyResponse = await fetch(request)
            .then(response => this.validate(response, request.headers))
            .then(validResponse => this.extractBody(validResponse))
            // Here is where the response body is being used to initialise one of the custom models that we are passing in. Code below
            .then(extractedBody => this.buildModel<T>(model, extractedBody))
            .catch((error) => { throw this.handleError(error); });
        return bodyResponse;
    }

    private static buildModel<T>(
        Model: Constructable<T>,
        params: ResponseBody,
    ): T {
        return new Model(params);
    }
}

我预计我不必将模型传递给方法 postAsync()并且它总是会返回一个 CustomModel 对象。但实际上我得到了这个错误 Type Constructable<CustomModel> is not assignable to type Constructable<T>

Example in Playground, hover over Constructable in args to see error

最佳答案

我解决了这个问题,即在未通过模型的情况下返回默认值(在本例中为通用对象)。 一般来说,修复是:

  • 将模型输入更改为 Constructable接口(interface),但要使用 Constructable<T> | object 的联合类型.
  • 更改将模型传递给对象的默认设置。
  • buildModel()函数检查模型的类型,如果它是对象,则返回传入的值,如果它是可构造的,则创建它的实例。

查看它是如何在 postAsync 中实现的参数,在 ResponseModel界面和 buildModelrequestAsync 中实现的方法:

interface Constructable<T> { new(params : any): T ;}
type ResponseModel<T> = Constructable<T> | Object;

export default class WebapiBase {
  static async postAsync<T = Object>(
      {
          uri = '',
          body = {},
          headers = new CustomHeaders(),
      }: PostRequestParams = {},
      // Here is where the defualt is implemented
      model: ResponseModel<T> = Object): Promise<T> {
      return this.requestAsync(model, HTTP_METHOD.POST, uri, headers, body);
  }
  private static async requestAsync<T = Object>(
      // This param accepts either a class or object
      model: ResponseModel<T>,
      method: HTTP_METHOD,
      uri: string,
      headers: CustomHeaders,
      body?: object): Promise<T> {
      const url = new URL(uri, window.location.origin);
      const request = this.buildRequest(url, method, headers, body);
      const bodyResponse = await fetch(request)
          .then(response => this.validate(response, request.headers))
          .then(validResponse => this.extractBody(validResponse))
          // Class instance or object returned here
          .then(extractedBody => this.buildModel(model, extractedBody))
          .catch((error) => { throw this.handleError(error); });
      return bodyResponse;
  }

  // Method that conditionally creates an instance of the passed in model
  // Or returns the object passed in if no model specified
  private static buildModel<T = Object>(
        Model: ResponseModel<T>,
        params: any,
    ): T {
        if (typeof Model === 'object') return params;
        return new Model(params);
  }
}

关于typescript - 当参数的类型是泛型时,是否可以在 typescript 中为参数设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56364384/

相关文章:

typescript - 将多个 typescript 文件合并为一个 typescript 定义文件

Angular 错误 TS2554 :Expected 0 arguments, 但在管道运算符上得到 x

c# - 从 IList<T> 转换为非泛型 IList

java - 在我的 contains 和 equals 方法中使用 Object 对象之前,是否必须将其转换为特定类型?

java - 用Java将对象强制转换为long

javascript - Angular 剑道网格

typescript - Angular 2 Firebase Observable promise 不返回任何东西

java - 如何使用 Jackson 反序列化泛型类?

c# - 温莎通用装饰器

c# - 将对象转换为通用类型的方法