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

Is there a way to solve a type declaration that accepts a union of a string and a function?

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

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 可以 return 函数或字符串,具体取决于根据特定内部逻辑接收到的输入值。所以类型 Type4 也可以是字符串,而不仅仅是 returning 字符串的方法。当前类型声明仅提供类型 Type4 作为输出,它缺少一个简单的字符串。事实上,在 returning 一个字符串时,这里是错误:

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

所以我想给myLibrary

的return值加上一个字符串
export default function myLibrary(arg1?: Type1, arg2?: Type2, 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 的所有问题,但这不是我想要实现的。

解决方案确实是使用 Overloads 概念,感谢@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;