微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法解决接受字符串和函数联合的类型声明?

如何解决有没有办法解决接受字符串和函数联合的类型声明?

我有这个类型定义,目前不完整:

export type Type1 = string;

export type Type2 = string | { [index: string]: any } | Array<string | undefined | boolean>;

export type Type3 = { [index: string]: any } | Array<string | undefined | boolean>;

export type Type4 = (arg1?: Type2 | Type3,arg2?: Type3) => string | undefined;

export default function myLibrary(arg1?: Type1,arg2?: Type2,arg3?: Type3): Type4;

通常该库用于以下示例之一的场景中,类型声明在此示例中正常工作,在 React 应用程序中:

const myCustomLibrary = myLibrary('string')
...
<span className={myCustomLibrary({
  key: value
})}/>

其中 value 可以是布尔值、字符串、对象..

但我说不完整的定义是因为它没有涵盖以下场景,仍在 React 应用程序中:

<span className={myLibrary('string',{
  key: value
})}/>

基本上 myLibrary 可以返回一个函数一个字符串,这取决于根据特定内部逻辑作为输入接收的值。所以类型 Type4 也可以是一个字符串,而不仅仅是一个返回字符串的方法。当前类型声明仅提供类型 Type4 作为输出,它缺少一个简单的字符串。事实上,当返回一个字符串时,这里是错误

TS2322: Type 'Type4' is not assignable to type 'string'.

所以我想在myLibrary的返回值中添加一个字符串

export default function myLibrary(arg1?: Type1,arg3?: Type3): Type4 | string;

但这会破坏当前正在运行的其他场景(接收实际 Type4 的场景并出现此错误

Cannot invoke an expression whose type lacks a call signature. Type 'string | Type4' has no compatible call signatures.ts(2349)

感觉有漏洞,我做错了什么? 我可以解决所有将 Type4 定义为 any 的问题,但这不是我想要实现的。

解决方法

解决方案确实是使用重载概念,感谢@AlekseyL。对于评论中的提示,为了更清晰的参考,我在此处添加了正确的代码修复。

export default function myLibrary(arg1?: Type1,arg2?: Type1): Type4;

export default function myLibrary(arg1: Type1,arg2: Type3 | undefined): string;

export default function myLibrary(arg1: Type1,arg2: Type2,arg3: Type3): string;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。