Home > Blockchain >  Typescript - get the function signature from a callback
Typescript - get the function signature from a callback

Time:02-20

I keep running into this situation: I'm handing off a callback as a parameter to a function or class that's in another file. Unfortunately I can't import the callback's signature because it came from a parent and I'd end up with a circular reference.

file Foo.ts

import fn from "./fn"

class Foo {

    bar() {
        fn( this.baz.bind(this) )
    }

    baz() { }
}

file fn.ts

import Foo from "./Foo" // circular reference

export default function ( callback: typeof Foo.prototype.baz ) { }

== Edit ==
Idea from @youdateme's linked article: break it into smaller pieces:

Foo.ts

import fn from "./fn"
import abstractFn from "./abstractFn"

class Foo {

    bar() {
        fn( this.baz.bind(this) )
    }

    baz(...args: Parameters<typeof abstractFn>) {
        abstractFn(...args)
    }
}

fn.ts

// import Foo from "./Foo" // circular reference
import abstractFn from "./abstractFn"

export default function ( callback: typeof abstractFn ) { }

CodePudding user response:

I'm guessing you're compiling to CommonJS which is why you can't use circular dependencies.

Of course, it's best to avoid them, which is why you can try this article to fix them .

ESM has built-in support for top-level await and circular dependencies, so I'd reckon switching over would solve it.

Change your compiler options to compile to es6 modules or higher.

Then add "type": "module" to your package.json to specify that you are using ESM.

Recompile your TypeScript and run (ESM needs node >14 iirc).

  • Related