我运行了一个方法,该方法最终将一个对象添加到属性extends IServerResponse
之一的数组中。
activeRequests: Array<ActiveRequest>;
interface ActiveRequest {
transactionId: string;
resolve: <T extends IServerResponse>(value: T) => void;
reject: (reason: Error) => void;
timer: NodeJS.Timeout;
progress: undefined | ((progress: Progress) => void);
}
// Example request start
export interface GetActiveProjectServerResponse extends IServerResponse {
type: 'response';
cmd: 'otii_get_active_project';
data: {
project_id: number;
}
}
async run(): Promise<GetActiveProjectResponse> {
let serverResponse = await new Promise<GetActiveProjectServerResponse>((resolve, reject) => {
this.connection.push(
this.requestBody,
this.transactionId,
this.maxTime,
resolve as (value: GetActiveProjectServerResponse) => void,
reject
);
});
}
// Example request end
public push<T extends IServerResponse>(
requestBody: any,
transactionId: string,
maxTime: number,
resolve: (value: T) => void,
reject: (reason: Error) => void,
progress?: (progress: Progress) => void
): void {
this.activeRequests.push({
transactionId,
resolve,
reject,
timer,
progress
});
}
public onMessage(event: { data: WebSocket.Data }): void {
...
let req = this.activeRequests.find(request => {
return request.transactionId === transactionId;
});
req.resolve(serverMessage);
}
但是在this.activeRequests.push(...)
行上出现错误:
[ts]
Argument of type '{ transactionId: string; resolve: (value: T) => void; reject: (reason: Error) => void; timer: Timeout; progress: ((progress: number) => void) | undefined; }' is not assignable to parameter of type 'ActiveRequest'.
Types of property 'resolve' are incompatible.
Type '(value: T) => void' is not assignable to type '<T extends IServerResponse>(value: T) => void'.
Types of parameters 'value' and 'value' are incompatible.
Type 'T' is not assignable to type 'T'. Two different types with this name exist, but they are unrelated.
Type 'IServerResponse' is not assignable to type 'T'.
我不明白。为什么T不兼容?我传递了相同的resolve函数,但具有相同的类型限制。
如何解决此问题?
答案 0 :(得分:1)
您没有包括导致错误的行,但是问题可能是ActiveRequest
“承诺”来处理扩展了T
的任何IServerResponse
,但是您尝试创建仅处理GetActiveProjectServerResponse
的一个。您可以这样修复它:
interface ActiveRequest<TResponse as IServerResponse> {
transactionId: string;
resolve: (value: TResponse) => void;
reject: (reason: Error) => void;
timer: NodeJS.Timeout;
progress: undefined | ((progress: Progress) => void);
}
activeRequests: Array<ActiveRequest<any>>;
...
const req: ActiveRequest<GetActiveProjectServerResponse> = {
...
resolve: (value: GetActiveProjectServerResponse) => {},
}
activeRequests.push(req)
TypeScript不会检查您的请求实际上是否为GetActiveProjectServerResponse
,但这并不重要,因为serverMessage
可能仍未输入任何类型。