[英]Typescript generic interface with union type
我想使用这样的通用联合类型的接口:
interface IOperator {
<U>(a: U[], b: U[] | U): boolean
}
export const intersects: IOperator = (a, b) => a.some((el) => b.includes(el))
export const includes: IOperator = (a, b) => a.includes(b)
但是,TS 给了我关于其中一种联合类型的错误:
Property 'includes' does not exist on type 'U | U[]'.
Property 'includes' does not exist on type 'U'.
我如何在这里正确地进行类型转换?
我试过了:
export const intersects: IOperator = (a, b) => a.some((el) => (b as U[]).includes(el))
但是,这给了我一个错误:
Cannot find name 'U'.
那么如何处理泛型联合类型呢?
我知道对于intersects
方法,输入b
的类型应仅为 arrays,对于includes
方法,输入b
的类型绝不应为 arrays。 接口的想法是不要重复自己,因为我有很多方法,其中一些要求b
是一个数组,而另一些则不是一个数组。 我会尽量避免创建两个单独的接口。
谢谢!
我认为:
export const intersects: IOperator = (a, b) => a.some((el) => Array.isArray(b)&&b.includes(el))
应该管用。 否则,b 可能不是 U 类型的数组,因此包含不可用。
在这里使用强制转换的问题是,如果B
的值与您的强制转换不匹配,您将遇到运行时错误。 话虽如此,您的用例可能是有效的,我们只是没有可用的上下文来查看它。 否则,您可能需要按照您帖子的某些评论的建议进行运行时检查。
此解决方案使用function
授予您对U
的访问权限,然后将 function 分配给const
以便您可以键入检查您的 function 是否与您的签名接口匹配。
interface IOperator {
<U>(a: U[], b: U[] | U): boolean
}
function _intersects <U>(a: U[], b: U[] | U): boolean {
return a.some((el) => (b as U[]).includes(el));
}
export const intersects: IOperator = _intersects;
function _includes <U>(a: U[], b: U[] | U): boolean {
return a.includes(b as U);
}
export const includes: IOperator = _includes;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.