Is there a shorthand in TypeScript for specifying only some optional types for generic types? For example, let's say I have a class with optional types:
class GenericClass<A extends Type1 = Type1, B extends Type2 = Type2, C extends Type3 = Type3>
I want to create a subclass like:
class Subclass extends GenericClass<TypeB>
, which should be equivalent to class Subclass extends GenericClass<Type1, TypeB, Type3>
. However, this approach results in an error as TypeScript tries to infer TypeB
as a subtype of Type1
. It would be helpful for me, particularly in defining generic React components where I need to specify the state type but not necessarily the props.
Am I correct in assuming that all preceding optional types must be provided when specifying an optional type? Or is there a way to achieve what I'm attempting?
In the case of optional function arguments, one can simply specify undefined
for the preceding optionals. This method doesn't work for generics though. I also attempted using void
instead, but to no avail. Additionally, I tried syntax like
Subclass extends GenericClass<B = TypeB>
, but that also proved unsuccessful.
I've come across suggestions to replace optional function arguments with an interface, such as:
interface Args { a?: number, b?: string, c?: any}
function myFunc(Args) {}
This allows calling myFunc({b: "value"});
without needing to do myFunc(undefined, "value");
. While this solution feels inadequate, is it possible to apply something similar to generic types? I'm uncertain about how that could be implemented.
Another approach I experimented with involved overloading the type like
type GenericClass<B extends Type2> = GenericClass<Type1, B, Type3>
. Unfortunately, this method failed unless I used a different name, like GenericClassB
.