TypeScript无法在通用方法中推断约束类型?

时间:2019-05-27 12:37:09

标签: typescript type-inference

我是具有强大C#背景知识的TypeScript的新手。

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

TypeScript:

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);

C#

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);
}

这是TS编译器的类型推断算法的问题(也许还不存在吗?),或者是我缺少一些根本原因并使之在TS中无法实现?

1 个答案:

答案 0 :(得分:1)

Typescript具有结构化的类型系统(当从C#发出时,这似乎有些奇怪,我知道我也遇到了同样的问题)。这意味着您有一个未使用的类型参数,编译器将忽略它,因为对于类型兼容性而言,它并不重要。将使用TResult的任何成员添加到IRequest并按预期工作:

interface IResult { }

interface IRequest<TResult extends IResult> { 
    _r?: undefined | TResult
}

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);
console.log(result.prop);

FAQ对此进行了解释。

相关问题