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

时间:2019-02-12 15:44:54

标签: typescript

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

1 个答案:

答案 0 :(得分:0)

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

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

现在不必提供type参数。

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