1

How do I declare a type that is a method of an imported module?

Suppose I have a simple file with functions:

// MyModule.ts

export const Method1 = () => {}
export const Method2 = () => {}
export const Method3 = () => {}

Now suppose I wanted to make a cool function that took one of those functions above as a parameter and then called it.

// OtherModule.ts

import * as methods from './MyModule'

//pesudocode that doesn't work
const CoolFunction = (method: typeof methods) => {
    method()
}

I want the method I pass to CoolFunction to be type checked. How do I do that?

// LastModule.ts
import * as m from './MyModule'
import { CoolFunction } from './OtherModule'

// typescript should yell at me if I try to do this
const badFunction = () => void
CoolFunction(badFunction)

// but any of these should be allowed
CoolFunction(m.Method1)
CoolFunction(m.Method2)
CoolFunction(m.Method3)
2
  • So just one of those 3 functions and no others ? Commented Dec 17, 2021 at 21:00
  • @TitianCernicova-Dragomir updated Commented Dec 17, 2021 at 21:08

1 Answer 1

3

You could use branded type on methods.

// Should work with imports too
namespace methods {
    const methodKey = Symbol.for("methodKey");
    export const Method1 = Object.assign(() => {}, { __brand: methodKey });
    export const Method2 = Object.assign(() => {}, { __brand: methodKey });
    export const Method3 = Object.assign(() => {}, { __brand: methodKey });
}

const CoolFunction = (method: typeof methods[keyof typeof methods]) => {
    method()
}


const badFunction = () => { }
CoolFunction(badFunction) //error

CoolFunction(methods.Method1) // ok

Playground Link

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

1 Comment

I like this, but wouldn't it be better to use a unique symbol which can't be retrieved and can't clash in the registry?

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.