I'm writing a type definition file (index.d.ts
) for a jQuery library that doesn't come with a type definition.
The methods of that library repeatedly accept parameters of the same multi-type (string | number | []
) so I defined it as a CustomType
:
export type CustomType = string | number | [];
declare global {
interface JQuery<TElement = HTMLElement> {
setFoo(foo: CustomType): this;
setBar(bar: CustomType): this;
}
}
When I now want to call setFoo()
on a jQuery object, the type hinting (of IntelliJ) shows that a parameter foo: CustomType
is expected which doesn't help fellow devs without looking up what that type resembles.
Instead I'd love to see the type hinting to show foo: string | number | []
.
For example, in C++ there is this concept of an inline
function which basically tells the compiler to put the code of the inlined functions body right into the block where it's called rather than to call / jump to the function. Is there something similar in TypeScript?
How can I force TypeScript to inline this CustomType
and make it show as foo: string | number | []
instead of foo: CustomType
?
Ugly Solution
declare global {
interface JQuery<TElement = HTMLElement> {
setFoo(foo: string | number | []): this;
setBar(bar: string | number | []): this;
}
}
One solution would be to eliminate the CustomType
and explicitly type parameters with their multi-types, but this becomes rather inconvenient with an increasing number of methods that use the same type as it doesn't benefit from reusability plus it looks ugly to me.
Imaginary Solution
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;
}
}
This would be ideal and in my imagination behave like the 'Ugly Solution', but unfortunately isn't supported. So what would be the proper way to achieve this?
[]
is specifically a zero-length tuple, and not an arbitrary array likeany[]
orArray<any>
. Is that the type you really want? – Shorttermstring | number | []
is simple enough that anything I can come up is, in my opinion, uglier. Like, would this be something you'd want to use? – Shortterm[]
. I meant to useany[]
. I'd consider your approach of declaring aconst
and then usingtypeof
to get the type a little hacky, but given that thisCustomType
is used in quite a few places in that lib, I'm still willing to accept your code snippet as a valid answer for the sake of reusability and maintenance. – SherbornCustomType
does not change anything in this regard. From my understanding,export
just allowsimport
to be used. And it seems to be good practice toexport
all your types and interfaces. – Sherborn