如何声明一个全部实现接口的元素数组



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']
        };
    }
}

可以为类型参数使用默认值。

interface ActiveRequest<TServerResponse extends IServerResponse = IServerResponse> {
    resolve: (value: TServerResponse) => void;
    ...
}

现在不必提供类型参数。

export class Connection {
    ...
    protected activeRequests: Array<ActiveRequest>;
    ...
}

最新更新