【发布时间】:2021-01-31 19:23:59
【问题描述】:
我正在为一个没有类型定义的 jQuery 库编写类型定义文件 (index.d.ts)。
该库的方法重复接受相同多类型(string | number | [])的参数,因此我将其定义为CustomType:
export type CustomType = string | number | [];
declare global {
interface JQuery<TElement = HTMLElement> {
setFoo(foo: CustomType): this;
setBar(bar: CustomType): this;
}
}
当我现在想在 jQuery 对象上调用 setFoo() 时,(IntelliJ 的)类型提示显示参数 foo: CustomType 是预期的,如果不查找该类型的相似之处,它不会帮助其他开发人员。
相反,我希望看到提示显示 foo: string | number | [] 的类型。
例如,在 C++ 中有一个 inline 函数的概念,它基本上告诉编译器将内联函数体的代码直接放入调用它的块中,而不是调用/跳转到函数。 TypeScript 中有类似的东西吗?
如何强制 TypeScript 内联此 CustomType 并使其显示为 foo: string | number | [] 而不是 foo: CustomType?
丑陋的解决方案
declare global {
interface JQuery<TElement = HTMLElement> {
setFoo(foo: string | number | []): this;
setBar(bar: string | number | []): this;
}
}
一种解决方案是消除 CustomType 并使用它们的多类型显式类型参数,但是随着越来越多的方法使用相同类型,这变得相当不方便,因为它没有从可重用性中受益,而且看起来对我来说很丑。
想象的解决方案
export type CustomType = string | number | [];
declare global {
interface JQuery<TElement = HTMLElement> {
setFoo(foo: inline CustomType): this; // <-- note the 'inline' here
setBar(bar: inline CustomType): this;
}
}
这将是理想的,并且在我的想象中表现得像“丑陋的解决方案”,但不幸的是不支持。那么实现这一目标的正确方法是什么?
【问题讨论】:
-
请注意,
[]类型是一个长度为零的元组,而不是像any[]或Array<any>这样的任意数组。那是你真正想要的类型吗? -
string | number | []很简单,在我看来,我能想到的任何东西都更丑陋。比如,this 是你想要使用的东西吗? -
由于我现在无法测试它,出于好奇,如果不导出 CustomType 会怎样?这有什么改变吗?
-
@jcalz 感谢有关
[]的提示。我的意思是使用any[]。我会考虑您声明const然后使用typeof使类型有点hacky 的方法,但是鉴于该CustomType在该库中的很多地方使用,我仍然愿意为了可重用性和维护性,接受您的代码 sn-p 作为有效答案。 -
@IngoBürk 不导出
CustomType在这方面没有任何改变。据我了解,export只允许使用import。export你所有的类型和接口似乎是一个好习惯。
标签: typescript inline type-definition