Calling all TypeScript gurus!
I am currently developing a versatile TypeScript function that can handle two different types of arguments: Class A and B.
A and B are completely independent and not related through inheritance.
The challenge I am facing is preventing any ambiguous usage of the function when called with the union type A | B
.
Is there a way to define this in TypeScript without separating the function into multiple functions for each type?
class A {/* snip */}
class B {/* snip */}
let a: A = new A();
fn(a); // specific usage allowed
let b: B = new B();
fn(b); // specific usage allowed
let c: (A | B) = someCondition ? new A() : new B();
fn(c); // should result in TypeScript compilation error due to ambiguity.
Update: Thank you for your responses! Apologies for the confusion earlier, as the scenario provided was not entirely accurate. I actually require a function that can accept a collection of multiple arguments using a rest parameter, as shown below:
class A {/* snip */}
class B {/* snip */}
let a: A = new A();
let b: B = new B();
let c: (A | B) = someOtherCondition ? new A() : new B();
interface Fn {
(...args: V[]) => void;
}
const fn: Fn = (...args) => {/* snip */};
fn(a); // single specific argument allowed
fn(b); // single specific argument allowed
fn(a, b, a, b); // multiple specific arguments still allowed
fn(c); // calling the function with an ambiguous argument should trigger a TypeScript compilation error.