首页 > 解决方案 > 为什么具有多种类型的泛型在可视代码中触发编译时错误

问题描述

我正在尝试创建一个带有多个参数的泛型类型函数。

这应该很容易,但是当我将某些类型混合在一起时,我就会得到compile-time可视化代码。

请参阅下面的示例

这个作品。。

class Test<T>{
    GetValue(value: string|boolean|number|undefined) {
        return value;
    }
}

new Test<Item>().getValue(4)
new Test<Item>().getValue(true)

这也有效

    class Test<T>{
        GetValue<B>(value: (x: T) => B) {
            return value;
        }
    }

    new Test<Item>().getValue(x=> x.name)

但是这个剂量不起作用。为什么?

    class Test<T>{
        GetValue<B>(value: (x: T) => B|string|boolean|number|undefined) {
            return value;
        }
    }
    // this work
    new Test<Item>().getValue(x=> x.name)
    
    // this do not work Why is that?
    new Test<Item>().getValue(true)

标签: typescripttypescript-genericsreact-typescript

解决方案


运算符优先级问题:

(x: T) => B|string|boolean|number|undefined

应该:

((x: T) => B)|string|boolean|number|undefined

否则参数value被认为是一个返回的函数B|string|boolean|number|undefined

操场


推荐阅读