Typescript可选的泛型类型

Typescript可选的泛型类型

本文介绍了Typescript可选的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下日志记录方法:

pre $ private logData< T,S>(operation:string,responseData:T, requestData?:S){
this.logger.log(operation +''+ this.url);
if(requestData){
this.logger.log('SENT');
this.logger.log(requestData);
}
this.logger.log('RECEIVED');
this.logger.log(responseData);
返回responseData;

requestData 是可选的,我希望能够在不发送消息时指定 S 类型来调用 logData requestData 指向该方法:而不是: this.logData< T,任何>('GET',data),我想调用 this.logData< T>('GET',data)。有没有办法实现这一点?

解决方案
按照TypeScript 2.2(您可以在TS Playground中试用) code> this.logData(GET,data)(带有 data 类型 T )成功推断为 this.logData< T,{}>(GET,data)



如果使用您使用的TS版本推断失败,则可以应用David Bohunek建议的重载。无论如何,确保第二个签名是在声明之前定义的,否则它不会参与可用的重载。

  //声明
private logData< T>(operation:string,responseData:T);
private logData< T,S>(operation:string,responseData:T,requestData ?: S);
//定义
private logData< T,S>(operation:string,responseData:T,requestData ?: S){
// Body
}


I have the following logging method:

  private logData<T, S>(operation: string, responseData: T, requestData?: S) {
    this.logger.log(operation + ' ' + this.url);
    if (requestData) {
      this.logger.log('SENT');
      this.logger.log(requestData);
    }
    this.logger.log('RECEIVED');
    this.logger.log(responseData);
    return responseData;
  }

The requestData is optional, I want to be able to call logData without having to specify the S type when I don't send the requestData to the method: instead of: this.logData<T, any>('GET', data), I want to call this.logData<T>('GET', data). Is there a way to achieve this?

解决方案

As per TypeScript 2.2 (you can try it in the TS Playground), calling this.logData("GET", data) (with data of type T) gets inferred succesfully as this.logData<T, {}>("GET", data).

The overload suggested by David Bohunek can be applied if the inference fails with the TS version you use. Anyway, ensure that the second signature is before declared and then defined, otherwise it would not participate in the available overloads.

// Declarations
private logData<T>(operation: string, responseData: T);
private logData<T, S>(operation: string, responseData: T, requestData?: S);
// Definition
private logData<T, S>(operation: string, responseData: T, requestData?: S) {
    // Body
}

这篇关于Typescript可选的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:10