Typescript 通用参数默认值

Typescript 通用参数默认值,typescript,generics,typescript-generics,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 =&g

我有以下代码用于使用
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();
    });
我假设解锁是类型参数
,但我看到的是类型脚本错误

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 '{}'.
类型“OnDataAccumulator”不能分配给类型“OnDataAccumulator”。
类型“string”不可分配给类型“T”。
“string”可分配给“T”类型的约束,但“T”可以用约束“{}”的不同子类型实例化。
  • 正确的方法是什么
  • 从消费者的角度来看,如果它在
    正文
    类型中是通用的,这会更完整吗
  • 同样,在每个
    req.write
    req.end
    中为回调提供impl是否更完整
  • “累加器”是该对象的正确术语吗

makeOnDataStringAccumulator
仅在使用
string
实例化类型时才起作用。我认为您应该使用重载函数签名,而不是默认类型参数。我认为默认参数通常比Typescript中的方法重载更可取。我知道通用参数默认值在TS中是可能的,所以我认为我所拥有的是接近的,但缺少一些小细节。是的,建议使用这些默认值,但它们不包括所有这样的场景。Yuu不能在这里使用它们,因为第二个参数的默认值仅在使用其默认值实例化类型参数时才兼容。如果在仅声明的上下文中编写单个签名,则可以清楚地看到这一点。这有意义吗?
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 '{}'.