Issue
I have the following scenario:
interface Foo<GenericA, GenericB> {}
I want to declare a variable of type Foo, but only specify the second generic, e.g.:
const foo: Foo<GenericBType>;
I can only do that if I write
const foo: Foo<unknown, GenericBType>;
It is not really that bad, but it doesn't feel right either, as I just want to make use of the second type, and I am not interested in the first at all.
Is there any other way I can write this in a more succinct way?
PS: This is about the expressjs types. I want to type the Request object, but I only want to consider the type of the Query params, which is the fourth generic in the type of the Request:
interface Request<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = core.Query,
Locals extends Record<string, any> = Record<string, any>
> extends core.Request<P, ResBody, ReqBody, ReqQuery, Locals> {}
so I would have to write something like:
req: Request<unknown, unknown, unknown, Foo>
and it's really not beautiful...
Solution
The simplest solution here is to create type alias:
interface Foo<GenericA, GenericB> { }
type Foo2<B> = Foo<unknown, B>
declare const foo: Foo2<'generic B'>
If all generics are optional then if you provide only one generic argument TS compiler will treat it as a first generic. There is no wildcard like _
or *
. I think using unknown
is the best way to handle missing generics.
You might looking for existential types (issues/10571). This is not supported by typescript. Existential types feature was supported in Flow but as you might have noticed it is deprecated now due to unsafety:
Triggers when you use the
*
(existential) type, as this type is unsafe and usually just equivalent to any. The effect of*
can generally be achieved by simply not providing a type annotation.
Answered By - captain-yossarian
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.