LCIII
LCIII

Reputation: 3626

Typescript type that is method of a module

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)

Upvotes: 1

Views: 128

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249656

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

Upvotes: 3

Related Questions