Packages & Modules
Organizing and sharing code
Introduction
In this lesson, you'll learn about packages & modules in TypeScript. Coming from Go, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Go, you're familiar with organizing and sharing code.
TypeScript has its own approach to organizing and sharing code, which we'll explore step by step.
The TypeScript Way
Let's see how TypeScript handles this concept. Here's a typical example:
// package.json defines the package
// tsconfig.json configures TypeScript
// mathutil.ts
export function add(a: number, b: number): number {
return a + b;
}
// Not exported — module-private
function helper(): void {}
// main.ts
import { add } from "./mathutil";
// or: import * as math from "./mathutil";
console.log(add(2, 3));
// External packages via npm
import axios from "axios";Comparing to Go
Here's how you might have written similar code in Go:
// go.mod defines the module
// module github.com/user/myapp
// go 1.21
// mathutil/mathutil.go
package mathutil
// Exported (capital) — public
func Add(a, b int) int { return a + b }
// Unexported (lowercase) — package-private
func helper() {}
// main.go
package main
import (
"fmt"
"github.com/user/myapp/mathutil"
)
func main() {
fmt.Println(mathutil.Add(2, 3))
}You may be used to different syntax or behavior.
Go uses go.mod; TypeScript/Node uses package.json + tsconfig.json
You may be used to different syntax or behavior.
Go exports by capitalization; TypeScript uses explicit export keyword
You may be used to different syntax or behavior.
Go imports are package paths; TypeScript imports are file paths or package names
You may be used to different syntax or behavior.
Go has no default exports; TypeScript supports both named and default exports
Step-by-Step Breakdown
1. Export Control
Go uses capitalization to control visibility. TypeScript uses explicit export/import keywords on each symbol.
func Add() {} // exported
func helper() {} // unexportedexport function add() {} // exported
function helper() {} // not exported2. Importing
Go imports full package paths; TypeScript imports relative file paths or installed npm package names.
import "github.com/user/myapp/mathutil"
mathutil.Add(2, 3)import { add } from "./mathutil";
add(2, 3);3. Package Manager
Go uses go get and go.mod for dependency management. TypeScript/Node uses npm/yarn/pnpm with package.json.
Common Mistakes
When coming from Go, developers often make these mistakes:
- Go uses go.mod; TypeScript/Node uses package.json + tsconfig.json
- Go exports by capitalization; TypeScript uses explicit export keyword
- Go imports are package paths; TypeScript imports are file paths or package names
Key Takeaways
- Go exports by capital letter; TypeScript uses export keyword
- go.mod → package.json + tsconfig.json
- go get → npm install
- Both use explicit import statements