I have this type:
type Bar = number;
type Foo = {
doIt: ((value: string) => Bar) | ((value: string, provideBar: (bar: Bar) => void) => void);
}
The idea is that Bar
can be returned in one of two ways depending on which function signature is provided. The code which consumes an implementation of Foo
looks like:
function getBar(foo: Foo) {
let bar: Bar = 0;
if (foo.doIt.length === 1) { // We've been provided with the first version of `Foo`
bar = foo.doIt('hello');
// The above line is erroring with:
// - bar: Type 'number | void' is not assignable to type 'number'
// - invocation of "doIt": Expected 2 arguments, but got 1.
} else if (foo.doIt.length === 2) { // We've been provided with the second version of `Foo`
foo.doIt('hello', (_bar) => bar = _bar);
}
}
Code which would provide an implementation of a Foo
looks like:
function provideBar() {
const foo1: Foo = {
doIt: (value) => 1. // Error: Parameter 'value' implicitly has an 'any' type.
}
const foo2: Foo = {
doIt: (value, provideBar) => provideBar(2) // Appears to be working
}
}
I'm hopeful typescript has a way to express what I'm trying to achieve. I'm not sure why I'm getting these errors as, the way I see it, TS has enough information to bar able to provide type inference (I'm assuming TS can use function.length
to deferentiate between the two ways to implement a Foo
)