将类成员的类型设置为通用参数的子类型

时间:2018-12-06 05:19:14

标签: tsc typescript3.0

我上了这个课:

export class Route <Req = any, Res = any, ReqBody = any, ResBody = any>{

  requestClass: Req;
  responseClass: Res;
  requestBodyClass: ReqBody;
  responseBodyClass: ResBody;

  constructor(){

  }

  setRequestType(v: Req): Req {
    this.requestClass = v;
    return v;
  }

  setResponseType(v: Res): Res{
    this.responseClass = v;
    return v;
  }

  setResponseBodyType(s: ResBody): ResBody {
    this.responseBodyClass = s;
    return s;
  }

  setRequestBodyType(s: ReqBody): ReqBody {
    this.requestBodyClass = s;
    return s;
  }

}

我的问题-有没有办法做这样的事情:

  requestClass: Req;
  responseClass: Res;
  requestBodyClass: ReqBody !== any ? ReqBody : Req['body'];
  responseBodyClass: ResBody !== any ? ResBody : Res['body'];

似乎不太可能执行类似的操作,但是,如果用户没有为ReqBody或ResBody传递类型,则我想将Req或Res上的body值默认为默认值。

0 个答案:

没有答案