【问题标题】:Is there a way to solve a type declaration that accepts a union of a string and a function?有没有办法解决接受字符串和函数联合的类型声明?
【发布时间】:2020-12-20 10:53:27
【问题描述】:

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

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, 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 的所有问题,但这不是我想要实现的。

【问题讨论】:

  • 如果不查看类型声明,我们将无法帮助您。请使用minimal reproducible example 来更新您的问题以证明问题,最好附上指向TypeScript playground 上相同代码的链接以显示问题。 (但请确保整个代码也问题中。)
  • 我认为这些其他类型不相关,但我还是添加了它们。你觉得够了吗?
  • 您是否正在寻找根据输入参数更改函数的返回类型?如果是这样,请查看重载
  • @axel - 这些帮助,但请参阅我上面的评论。一个完整的示例演示了问题,而我们无需猜测事物(例如 value 是什么),可以帮助人们帮助您。
  • 重载在这里会有所帮助。尚不清楚何时返回字符串,何时返回函数typescriptlang.org/play?#code/…

标签: reactjs typescript types type-declaration type-definition


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2021-01-08
    • 2013-01-18
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2018-08-02
    相关资源
    最近更新 更多