0

I'm working on a larger project type definition file. I have simplified the code into an isolated example:

Module definition f.d.ts

export type myFunction = ((r: string) => Promise<any>) // async def
  | ((r: string, done: (err: Error | null, b?: any) => void) => void) //callback def

export interface addFunc {
  (c: string, f: myFunction): void
}

export interface FI {
  addFunc: addFunc
}

export default function f(): FI

Module implementation f.js

function f () {
  return {
    addFunc: (c, p) => {
      this[c] = p
      return this
    }
  }
}

module.exports = f

Module utilization index.ts

import f from './f'

f().addFunc('x', (r, d) => { // Compiles as expected
  d(null)
})

f().addFunc('x', async (r) => { // Error ts(7006) Parameter 'r' implicitly has an 'any' type.
  return null
})

Can you please explain why this error is happening and how I could fix it? I believe the issue is in the type definition.

Please do not comment on the implementation itself; this is an extremely stripped down and isolated piece of a large API.

Thank you for the help!

1 Answer 1

2

You need to change it to

f().addFunc('x', async (r: string) => {
  return null
})

Without adding : string, your function is really a (r: any) => Promise<null>, which is not assignable to the type myFunction.

The first case in your example compiles because TypeScript is able to infer the types of r and d by the fact that there're two parameters, which makes it impossible to assign to the first case in the union definition of myFunction. But when a function has only one parameter, it could be assigned to a type that has one or more parameters, so TypeScript cannot automatically infer the type of r.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, I'll try this and see how it goes. I was hoping TS could infer this based on regular function overload patterns typescriptlang.org/docs/handbook/declaration-files/…
Marking this is as the correct answer because it is a valid fix. Ideally TS would be able to infer based on function overload; however, I'm not going to get blocked by it right now! Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.