Skip to content

Private Variables and Functions in Modules ​

Modules in TypeScript allow you to encapsulate variables and functions, making them private by default unless explicitly exported. This means that any variable or function not exported from a module remains private and inaccessible to other modules.

Example ​

Consider the following example where a module defines a private variable used in an exported function:

typescript
// mymodule.ts
export function getSecret() {
    return s;
}

// `s` is private since it isn't exported
let s = "secret";

The variable s is private to mymodule.ts and cannot be accessed directly from other modules. However, the function getSecret is exported and can be used to access the value of s.

typescript
// main.ts
import { getSecret } from "./mymodule";

console.log(getSecret());

In main.ts, we import the getSecret function from mymodule.ts and use it to log the secret value. The variable s remains private and is not directly accessible from main.ts.

Attempting to Access Private Variables ​

If you try to import or access the private variable s directly, you will encounter an error because it is not exported from the module.

typescript
// main.ts
import { getSecret, s } from "./mymodule"; 
// Error: 's' is not exported from './mymodule'

console.log(s); 
// Error: 's' is not defined