TypeScript无法在泛型方法中推断受约束的类型?

TypeScript无法在泛型方法中推断受约束的类型?,typescript,type-inference,Typescript,Type Inference,我是一个有很强C#背景的打字新手 我想知道,在TypeScript中,类型推断似乎在以下情况下不起作用,但在C#中起作用的确切原因是什么: 打字稿: interface IResult { } interface IRequest<TResult extends IResult> { } interface ISomeResult extends IResult { prop: string; } interface ISomeRequest extends IRequ

我是一个有很强C#背景的打字新手

我想知道,在TypeScript中,类型推断似乎在以下情况下不起作用,但在C#中起作用的确切原因是什么:

打字稿:

interface IResult { }

interface IRequest<TResult extends IResult> { }

interface ISomeResult extends IResult {
    prop: string;
}

interface ISomeRequest extends IRequest<ISomeResult> { }

 function Process<TResult extends IResult>(request: IRequest<TResult>): TResult {
    throw "Not implemented";
}

let request: ISomeRequest = {};
let result = Process(request);
// Error: Property 'prop' does not exist on type '{}'.
console.log(result.prop);
接口IResult{}
接口IRequest{}
接口异构体结果扩展了IResult{
道具:弦;
}
接口ISOMEQUEST扩展了IRequest{}
功能流程(请求:IRequest):TResult{
抛出“未执行”;
}
let请求:ISOMEQUEST={};
让结果=过程(请求);
//错误:类型“{}”上不存在属性“prop”。
console.log(result.prop);
C#

接口IResult{}
接口IRequest,其中TResult:IResult{}
界面异构体结果:IResult
{
字符串属性{get;set;}
}
接口请求:IRequest{}
静态TResult进程(IRequest请求),其中TResult:IResult
{
抛出新的NotImplementedException();
}
静态void Main()
{
ISOMEQUEST请求=默认值;
var结果=过程(请求);
//嗯
Console.WriteLine(result.Prop);
}

这是TS编译器的类型推断算法的问题(可能还没有),还是有一些基本的原因我不知道,使TS无法实现这一点?

Typescript有一个结构化的类型系统(来自C#时,这可能看起来有点奇怪,我知道我也遇到了同样的问题哇,你太快了,谢谢!这说明了一切。但是,解决方法似乎有些粗糙,常见问题解答说“一般来说,你不应该有未使用的类型参数。该类型将具有意外的兼容性(如图所示)并且在函数调用中也无法进行适当的泛型类型推断。”建议我最好不要走这条路。@AdamSimon这取决于你,添加成员确实有效,我有时使用它来满足类型系统。如果你能在请求中找到结果的有意义的用途,那将是理想的。可能是一个可选的转换函数或其他东西。这可能会在meanin中使用gful方式。实际上,这个解决方案只是为了比简单的命名约定更强烈地表达请求和结果类型之间的关系。当然,作为一个很好的副作用,它允许我编写更少的代码,因为我不需要在调用进程时键入结果类型。因此,毕竟使用它是可以的无害的把戏。
interface IResult { }

interface IRequest<TResult> where TResult : IResult { }

interface ISomeResult : IResult
{
    string Prop { get; set; }
}

interface ISomeRequest : IRequest<ISomeResult> { }

static TResult Process<TResult>(IRequest<TResult> request) where TResult : IResult
{
    throw new NotImplementedException();
}

static void Main()
{
    ISomeRequest request = default;
    var result = Process(request);
    // OK
    Console.WriteLine(result.Prop);
}