Reputation: 48899
Let me explain:
arg1
must be of Type1
or Type2
arg2
must be of Type1.options
(if arg1
is Type1
) or Type2.options
otherwisecreate(arg1: Type1 | Type2, arg2?: any) {}
It's possible to define this "bound" in TypeScript?
Upvotes: 1
Views: 366
Reputation: 51846
You can use a generic declaration to infer the dependency like this:
function create<T extends (Type1 | Type2)> (arg1: T, arg2?: T['options']) { ... }
You can also create an alias like type ArgType = Type1 | Type2
to simplify the generic constraint:
function create<T extends ArgType> (arg1: T, arg2?: T['options']) { ... }
Upvotes: 3
Reputation: 30879
You are looking for an overloaded function:
function create(arg1: Type1, arg2?: Type1.options);
function create(arg1: Type2, arg2?: Type2.options);
function create(arg1: Type1 | Type2, arg2?: Type1.options | Type2.options) { ... }
Do note that the last signature (the "implementation signature") is not one of the overload signatures and should be broad enough to cover all of the overload signatures. You'll sort out the actual arguments in the body of the function.
Upvotes: 2