gremo
gremo

Reputation: 48899

How to "bound" to parameters in TypeScript, making one type "depend" on other type?

Let me explain:

create(arg1: Type1 | Type2, arg2?: any) {}

It's possible to define this "bound" in TypeScript?

Upvotes: 1

Views: 366

Answers (2)

Patrick Roberts
Patrick Roberts

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

Matt McCutchen
Matt McCutchen

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

Related Questions