0

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)

3
  • This isn't "overloading" as the term is used in TypeScript. Overloads are essentially intersections of functions, while these are unions.
    – jcalz
    Feb 6, 2021 at 22:47
  • My apologies. Ignoring my terminology, do you have any ideas? Feb 6, 2021 at 22:54
  • Yeah I'm writing up an answer now.
    – jcalz
    Feb 6, 2021 at 22:56

1 Answer 1

2

For the issue inside getBar()'s implementation, you're running into microsoft/TypeScript#18422, listed as a design limitation in TypeScript.

The compiler only sees the length property of a function as being of type number, and not any specific numeric literal type like 1 or 2. So checking foo.doIt.length === 1 has no implication for control flow analysis, and thus the compiler does not know which of the two function types it is calling.

One major problem with checking length is that it might well not be what you think it is. Functions can be implemented with rest parameters, and length might well be 0.

Or because TypeScript allows you to assign functions that accept fewer parameters to those that accept more (see this FAQ entry), it's possible that a function that matches (value: string, provideBar: (bar: Bar) => void) => void might have a length of 1 or 0 because function implementations are free to ignore any of their inputs.

Because of such weirdness around length, TypeScript basically doesn't do anything and recommends that you don't try to check length this way.

Still, if you are confident that the check does what you think it does (that is, nobody will set "doIt" to one of the "gotcha" versions above), you can get similar behavior by implementing a user-defined type guard function:

function takesOneArg<F extends Function>(x: F): x is Extract<F, (y: any) => any> {
    return x.length === 1
}

The takesOneArg() function checks the length of its function-like argument of type F and returns true if it equals 1 and false otherwise. The return type predicate x is Extract<F, (y: any) => any> means that if F is a union of function types, a true result means that the type of x can be narrowed to just the members of F that take one argument; and a false result means x can be narrowed to the other ones.

Now your getBar() implementation works as expected:

function getBar(foo: Foo) {
    let bar: Bar = 0;
    if (takesOneArg(foo.doIt)) {
        bar = foo.doIt('hello');
    } else {
        foo.doIt('hello', (_bar) => bar = _bar);
    }
}

As for the issue when you create a Foo where you see an implicit any error in the callback argument, this seems to be microsoft/TypeScript#37580. You would like value to be contextually typed as string, but the compiler is not doing so. There's not a lot of info in that GitHub issue, so I can't say what's causing the poor interaction between the function union and contextual typing inference.

Assuming this doesn't get fixed anytime soon, the workaround is the same one I'd always recommend with implicit any problems: explicitly annotate the thing the compiler can't infer:

const foo1: Foo = {
    doIt: (value: string) => 1
}

That now compiles without error.


Playground link to code

2
  • Just processing your answer. Thanks for taking the time to write out such a detailed one. Feb 6, 2021 at 23:17
  • Damn, such a shame about the Foo creation issue... in reality the Foo type is much more complex and takes generics (of which inference is super important in reducing code noise. Infact, some of the types being used are from 3rd party libs which don't always export the required type!). Feb 6, 2021 at 23:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.