如何解决具有联合类型的 Typescript 通用接口
我想使用具有通用联合类型的接口,如下所示:
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
的类型应该只是数组,而对于 includes
方法,输入 b
的类型不应该是数组。接口的想法是不要重复我自己,因为我有很多方法,其中一些要求 b
是数组,而另一些则不是数组。我会尽量避免创建两个单独的界面。
谢谢!
解决方法
我认为:
export const intersects: IOperator = (a,b) => a.some((el) => Array.isArray(b)&&b.includes(el))
应该可以。否则,b 可能不是 U 类型的数组,因此包含不可用。
,此处使用强制转换的问题是,如果 B
的值与您的强制转换不匹配,则会出现运行时错误。话虽如此,您的用例可能是有效的,我们只是没有可用的上下文来查看它。否则,您可能需要按照帖子的一些评论的建议进行运行时检查。
此解决方案使用 function
为您提供对 U
的访问权限,然后将该函数分配给 const
,以便您可以键入检查您的函数签名是否与您的界面匹配。
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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。