typescript - 为什么具有多种类型的泛型在可视代码中触发编译时错误
问题描述
我正在尝试创建一个带有多个参数的泛型类型函数。
这应该很容易,但是当我将某些类型混合在一起时,我就会得到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)
解决方案
运算符优先级问题:
(x: T) => B|string|boolean|number|undefined
应该:
((x: T) => B)|string|boolean|number|undefined
否则参数value
被认为是一个返回的函数B|string|boolean|number|undefined
推荐阅读
- python - 损失函数中的正则化项进行数学运算和赋值
- javascript - 有没有办法通过动态索引(如链接{1}、链接{2}等)传递道具?
- php - 如何使用从数据库返回的日期调用自定义函数?
- magento - Magento 2.4 缓存不会真正清除
- postgresql - Postgres SQL - 每行滚动 24 小时权重的总和
- javascript - 如何将 ISO 日期映射到 Date 对象
- javascript - 为什么更改 MongoDB versionKey "_v" 时 bcrypt 会失败?
- python - 裁剪掉额外的透明像素后无法保存 PIL 图像文件
- excel - VBA 循环永远存在 - 我在哪里可以优化?
- serverless - 无服务器服务未填充到 New Relic APM 仪表板中