push
方法是用几个不同的请求中的任何一个调用的,它们都实现了签名中的接口。
如何更改此代码,以免在Array<ActiveRequest<any>>
中使用any关键字?
interface ActiveRequest<TServerResponse extends IServerResponse> {
resolve: (value: TServerResponse) => void;
...
}
export class Connection {
protected activeRequests: Array<ActiveRequest<any>>;
constructor(...) {
this.activeRequests = [];
...
}
public push<TRequestBody extends IRequestBody, TServerResponse extends IServerResponse>(
requestBody: TRequestBody,
resolve: (value: TServerResponse) => void,
)
...
this.activeRequests.push({
resolve,
...
});
}
以下是如何调用push
的示例:
export interface CreateProjectRequestBody extends IRequestBody {
cmd: 'otii_create_project';
}
export interface CreateProjectServerResponse extends IServerResponse {
cmd: 'otii_create_project';
data: {
project_id: number;
}
}
export type CreateProjectResponse = Project;
export class CreateProjectRequest extends Request {
constructor(
transactionId: string,
connection: Connection,
maxTime: number
) {
super(transactionId, connection, maxTime);
this.requestBody = {
type: 'request',
cmd: 'otii_create_project'
}
}
async run(): Promise<CreateProjectResponse> {
let serverResponse = await new Promise((resolve, reject) => {
this.connection.push(
this.requestBody,
this.transactionId,
this.maxTime,
resolve as (value: CreateProjectServerResponse) => void,
reject
);
}) as CreateProjectServerResponse;
return {
id: serverResponse['data']['project_id']
};
}
}
答案 0 :(得分:0)
您可以为类型参数使用默认值。
interface ActiveRequest<TServerResponse extends IServerResponse = IServerResponse> {
resolve: (value: TServerResponse) => void;
...
}
现在不必提供type参数。
export class Connection {
...
protected activeRequests: Array<ActiveRequest>;
...
}