通用参数默认值

时间:2019-12-13 23:52:23

标签: typescript generics typescript-generics

我有以下代码,用于使用https模块进行请求。

export const makeRequest = (requestOptions: RequestOptions, body?: string): Promise<string> =>
    new Promise((resolve, reject) => {
        const req = https.request(requestOptions, (res: IncomingMessage): void => {
            // TODO: This assumes the client wants a string--consider making generic
            res.setEncoding("utf8");
            let data = "";
            res.on("data", chunk => data += chunk);
            res.once("end", (): void => resolve(data));
        });
        req.once("error", error => reject(error));
        if (body) {
            req.write(body);
        }
        req.end();
    });

我想使这种泛型成为返回的类型,但默认为string,所以我进行了更改,现在有了以下内容(无法编译)。

export interface OnDataAccumulator<T> {
    encoding: string;
    listener: (chunk: any) => void;
    result: () => T;
}

const makeOnDataStringAccumulator: () => OnDataAccumulator<string> = () => {
    let data = "";
    return {
        encoding: "utf8",
        listener: (chunk: any) => data += chunk,
        result: () => data
    };
};

export const makeRequest = <T = string>(requestOptions: RequestOptions,
                               accumulator: OnDataAccumulator<T> = makeOnDataStringAccumulator(),
                               body?: string): Promise<T> =>
    new Promise((resolve, reject) => {
        const req = https.request(requestOptions, (res: IncomingMessage): void => {
            res.setEncoding(accumulator.encoding);
            res.on("data", accumulator.listener);
            res.once("end", (): void => resolve(accumulator.result()));
        });
        req.once("error", error => reject(error));
        if (body) {
            req.write(body);
        }
        req.end();
    });

我认为对此的解锁是类型参数<T = string>,但我看到打字稿错误

Type 'OnDataAccumulator<string>' is not assignable to type 'OnDataAccumulator<T>'.
  Type 'string' is not assignable to type 'T'.
    'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
  • 正确的方法是什么?
  • 从消费者的角度来看,如果它在body类型中是通用的,这样是否更完整?
  • 类似地,为每个req.writereq.end中的回调提供一个隐含的表示是否更完整?
  • “累加器”是该对象的正确术语吗?

0 个答案:

没有答案