- 01Getting Started
- 02Your First Output (console.log)
- 03Variables and Type Annotations (number/string/boolean)
- 04Array Types
- 05Function Types (Parameters and Return Values)
- 06Optional Parameters and Default Parameters
- 07Interfaces (interface)
- 08Optional Properties (?)
- 09Type Aliases (type)
- 10Union Types
- 11Literal Types
- 12enum (Enumerated Types)
- 13Classes and Types
- 14Inheritance (extends) and Implementing an Interface (implements)
- 15Generics (<T>)
- 16Tuple Types
- 17The any and unknown Types
- 18Type Assertions (as)
- 19The readonly Modifier
- 20[Applied] Build a Mini Inventory Management System
Classes and Types
This lesson covers the basics of writing a class in TypeScript. It's for anyone searching "TypeScript class usage."
The big difference from JavaScript is that a TypeScript class can have typed properties. The constructor receives initial values, and each property is declared with a type annotation.
The example defines class Animal with a name: string property and a speak() method that returns a sound.
A common early mistake is forgetting to declare a property in the class body. In a TypeScript class, it's not enough to just type the constructor's parameter โ you also need to declare the property in the class body itself, like name: string; (though adding public to the constructor's parameter lets you skip this).
In real projects, classes are used to represent data that bundles state and behavior together โ a game character, or a "product" or "user" in a business app.
๐งช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ nothing is sent anywhere).
