Ad space (banner)
Lesson 13 / 20

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.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช 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).

Ad space (banner)
Ad space (in-article)