I am trying to safely implement the following function
type OneOrAll<T extends any[]> =
T extends { length: 1 } ? T[0] :
T
interface Foo {
// ...
}
declare function oneOrAll<A extends Foo[]>(...as: A): OneOrAll<A>;
which should either return Foo or Foo[] depending on the length of the given parameters. For example
const x: Foo = oneOrAll(fooA);
const xs: Foo[] = oneOrAll(fooA, fooB);
The types work out already, but I am struggling to write the implementation. My first attempt was this
function oneOrAll<A extends Foo[]>(...as: A): OneOrAll<A> {
if (as.length == 1) {
return as[0]; // Type 'Foo' is not assignable to type 'OneOrAll<A>'.
}
return as; // Type 'A' is not assignable to type 'OneOrAll<A>'.
// Type 'Foo[]' is not assignable to type 'OneOrAll<A>'.
}
however this does not compile with the inlined errors. What is the proper way to implement this function?
asas an identifier in TypeScript is unfortunate.