使用泛型进行错误的类型推断 [英] wrong type inference with generics

查看:36
本文介绍了使用泛型进行错误的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有一个错误,有很多行文本.当我将箭头标记行中泛型的Y参数更改为数字或字符串等类型时一切正常,编译后没有错误

There is a error in the code below with the lots of lines of text. When I change the Y parameter of the generic in the arrow marked line to the type such as number or string all is ok, no error after compilation

问题 1 - 这是编译器错误吗?问题 2 - 如何修复错误?

Question 1 - is it a compiler bug ? Question 2 - how to fix the error ?

class channel<S,Y>{

public merge(...channels:channel<any, Y>[]) {

    var ch = new channel<void, channel<any, Y>>(); // <---

    var result = ch.flatMap(x => x);

    return result;
}

public flatMap<R>(projector: (data: Y) => channel<any, R>): channel<Y, R> {
    return null;
}
}

预期的结果类型是channel,但编译器推断出不同的东西

expected type of result is channel<any, Y>, but the compiler infers something different

错误信息:

Error   1   Supplied parameters do not match any signature of call target:
Call signatures of types '(x: channel<any, channel<any, Y>>) => channel<any, channel<any, Y>>' and 
                         '(data: channel<any, channel<any, Y>>) => channel<any, Y>' are incompatible:
    Types 'channel<any, channel<any, Y>>' and 'channel<any, Y>' originating in infinitely expanding type reference have incompatible type arguments.    

更新

public flatMap<R>(projector: (data: Y) => channel<any, R>): channel<any, R> {} // changed Y to any

public correct(...targets: channel<any, Y>[]) {
    var ch = new channel<void, channel<any, Number>>().named('merge');

    var result = ch.flatMap(x => x);


    return result;
}     

public incorrect(...targets: channel<any, Y>[]) {
    var ch = new channel<void, channel<any, Y>>().named('merge'); // changed Number to Y

    var result = ch.flatMap(x => x); // error


    return result;
}     

那里有一些魔法.当我这样改变时,我得到 (x:Number):Number =>x .但是当使用Y时,x是channel>

Some magic there. When I changed like that, I got (x:Number):Number => x . But when use Y, x is channel<any, channel<any,Y> >

推荐答案

预期的结果类型是channel

我不明白你是如何得出这个结论的.下面是这个类和函数的定义:

I don't see how you arrived at this conclusion. Following the definition of this class and function:

  1. ch的类型为channel>(显式给出)
    • ch#S = void
    • ch#Y = channel
  1. The type of ch is channel<void, channel<any, Y>> (explicitly given)
    • ch#S = void
    • ch#Y = channel<any, Y>

无论如何,因为你有一个无限扩展的泛型类型(参见 TypeScript 规范第 3.8.7 节),泛型类型推断必然会受到限制(我相信这个问题实际上是无法确定的).在这种情况下,您最好的选择是手动指定类型参数,或者通过为 x 提供类型注释来给编译器一个额外的提示.

Anyway, because you have an infinitely expanding generic type (see TypeScript spec section 3.8.7), generic type inference is going to be necessarily limited (I believe the problem is actually undecidable). Your best bet in this situation is going to be to specify the type parameter manually, or give the compiler an extra hint by providing a type annotation for x.

这篇关于使用泛型进行错误的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆