Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript is there a way to restrict / limit an exported function so it can only be imported by certain files?

I want developers to use a class / interface instead of importing functions directly.

Is there a way to limit so only the class can import the function?

I don't want to have to put all the functions in a single file as it's not scalable in a large project

i.e. I don't want to use this pattern:

// myclass.ts

// no exports on the functions
function foo(){ ... }
function bar(){ ... }

export class MyClass {
 Foo(){ return foo() }
 Bar(){ return bar() }
}

What I'm trying to achieve:

// foo.ts
export function foo(){ ... } 
// I want this to be private but it needs to be exported so the class below can use it

// bar.ts
export function bar() { ... }

// myclass.ts
import { foo } from 'foo';
import { bar } from 'bar';

export class MyClass {
 Foo(){ return foo() }
 Bar(){ return bar() }
}

// anyotherfile.ts
import { foo } from 'foo' // Stop from importing directly
import { MyClass } from 'myclass' // use this instead
like image 383
Tom Avatar asked Jan 30 '26 22:01

Tom


1 Answers

I'm assuming you're creating something that's meant to be installed as an npm package and that not everything in your project is just source-code dependencies.

If this is not your case then I suspect its likely impossible to achieve what you would like without magic. Typescript, as far as I know, has no notion of 'package level' exports as you would have in Java for example.

Ensure that the entry point to your library/package points to index.js

Let say you have the following structure: module/ functions/ MyClass.ts index.ts

//a.ts
export function a(): any // export this from files inside functions/

Then your class works as you wanted it to

//MyClass.ts
import { a } from './functions/a'
 
export class MyClass {
    a(): any {
         return a()
    }
}

Finally, to restrict access from outside the module to only the class, export only the class in the module's index file

//index.ts
export * from './MyClass'

Now anyone installing your package will not be able to import anything except MyClass from '@yourpackage-name'

Note however, they can always brute force an

import from @yourpackage-name/build/src/functions/a

Hope this helps.

like image 153
Gvozden Miskovic Avatar answered Feb 01 '26 16:02

Gvozden Miskovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!