#Merging types with rest parameter

5 messages · Page 1 of 1 (latest)

brave bough
#

Given these types

type SingleArg = <T>(input: ComplexType<T>) => boolean;
type MultiArg = <T>(...input: ComplexType<T>[]) => boolean;

Is there a way to merge them together into a single type which can then be constrained (somehow) to either accept a single input arg or the ...rest type

loud harness
#

i'm possibly confused, but <T>(...input: ComplexType<T>[]) => boolean; should already be able to accept a single arg

#

do you want to force it to have at least one argument (forbidding calls with no args like f())? if so:

type AtLeastOneArg = <T>(input: ComplexType<T>, ...rest: ComplexType<T>[]) => boolean;

or, equivalently:

type AtLeastOneArg = <T>(...input: [ComplexType<T>, ...ComplexType<T>[]]) => boolean;
brave bough
#

sorry about the delay in answering. my goal was (i say "was" because i pivoted from this solution) to get a function that accepts either 1 max argument or more.

i came up with this

type CombinedType<T extends 's' | 'c'> = T extends 's' ? <U>(input: ComplexType<U>) => boolean : <U>(...input: ComplexType<U>[]) => boolean;

it's clunky but it worked.

loud harness
#

"1 max or more" sounds contradictory to me (am i allowed to pass two arguments? 2 > 1 so that seems to violate "1 max"). if you meant "at least one (or more)" then see my previous suggestions (though i'm not sure what T is in your last snippet; maybe the 1/many distinction is conditional upon some other value?)