Structs & Classes
Defining data structures and behavior
Introduction
In this lesson, you'll learn about structs & classes 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 defining data structures and behavior.
TypeScript has its own approach to defining data structures and behavior, which we'll explore step by step.
The TypeScript Way
Let's see how TypeScript handles this concept. Here's a typical example:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return "Hi, I'm " + this.name;
}
birthday(): void {
this.age++;
}
}
const p = new Person("Alice", 30);
console.log(p.greet());
p.birthday();Comparing to Go
Here's how you might have written similar code in Go:
type Person struct {
Name string
Age int
}
// Method on struct
func (p Person) Greet() string {
return "Hi, I'm " + p.Name
}
// Pointer receiver (mutation)
func (p *Person) Birthday() {
p.Age++
}
p := Person{Name: "Alice", Age: 30}
fmt.Println(p.Greet())
p.Birthday()You may be used to different syntax or behavior.
Go uses structs + methods; TypeScript uses classes with encapsulated methods
You may be used to different syntax or behavior.
Go pointer receivers (*T) for mutation; TypeScript mutates via this
You may be used to different syntax or behavior.
TypeScript uses new keyword; Go uses struct literals
You may be used to different syntax or behavior.
TypeScript supports access modifiers (private, protected); Go uses capitalization
Step-by-Step Breakdown
1. Data Definition
A Go struct is just data; methods are defined separately. A TypeScript class bundles data and methods together.
type Person struct { Name string; Age int }class Person { name: string; age: number; ... }2. Methods
Go methods are defined outside the struct with a receiver. TypeScript methods live inside the class body.
func (p Person) Greet() string { return "Hi, I'm " + p.Name }greet(): string { return "Hi, I'm " + this.name; }3. Access Control
Go uses capitalization (exported = public, lowercase = package-private). TypeScript has explicit private/public/protected keywords.
class BankAccount {
private balance: number = 0;
public deposit(amount: number): void { this.balance += amount; }
}Common Mistakes
When coming from Go, developers often make these mistakes:
- Go uses structs + methods; TypeScript uses classes with encapsulated methods
- Go pointer receivers (*T) for mutation; TypeScript mutates via this
- TypeScript uses new keyword; Go uses struct literals
Key Takeaways
- Go struct + receiver methods → TypeScript class
- Go exported names (capital) → TypeScript public keyword
- Both support methods that mutate state
- TypeScript classes support inheritance; Go uses composition