~/
hackweb.dev
TypeScript Classes with Types
Quiz
⌘K
...
~/
/tutorials
/ts/ts-classes-types/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/ts/8ts-classes-types
Write
Preview
Diff
# TypeScript Classes with Types TypeScript adds type annotations to classes, making class-based code safer and more maintainable. ## Class Property Types Annotate properties to ensure values always match the expected type: ```typescript class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } let person = new Person("John", 25); person.age = 30; // OK person.age = "old"; // Error ``` ## Access Modifiers `public` (default), `private`, and `protected` control visibility: ```typescript class BankAccount { private balance: number; protected accountNumber: string; public owner: string; constructor(owner: string, balance: number, accountNumber: string) { this.owner = owner; this.balance = balance; this.accountNumber = accountNumber; } deposit(amount: number): void { if (amount > 0) this.balance += amount; } } ``` ## Constructor Shorthand `public`, `private`, or `protected` before a parameter creates and initializes the property automatically: ```typescript class User { constructor( public name: string, public age: number, private email: string ) {} } let user = new User("John", 25, "john@example.com"); console.log(user.name); // "John" ``` ## Implementing Interfaces Classes can implement interfaces to enforce a contract: ```typescript interface Shape { color: string; getArea(): number; } class Circle implements Shape { color: string; radius: number; constructor(radius: number, color: string) { this.color = color; this.radius = radius; } getArea(): number { return Math.PI * this.radius ** 2; } } ``` **Remember:** `readonly` properties cannot change after initialization. ## Best Practices - Always type class properties to prevent `any` inference - Use `implements` to enforce class contracts with interfaces - Use constructor shorthand for simple property assignments - Use `private`/`protected` for encapsulation - Use `readonly` for immutable properties ## Common Mistakes - Missing property types defaults to `any` - Not implementing interfaces means no enforced shape - Using `any` in constructors defeats type safety - Forgetting access modifiers makes everything public
No changes yet
Reset to original
Submit suggestion
cancel