我有以下代码,用于使用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.write
和req.end
中的回调提供一个隐含的表示是否更完整?