Skip to main content
Now let’s look at TypeScript classes and how they help model objects with state and behavior.
A minimalist slide showing the word "Classes" on a white background with a large teal curved shape on the right. A white icon of a vertical rectangle with three dots sits on the teal area, and a small "© Copyright KodeKloud" appears in the bottom-left.
Elmer wants each duck to have its own behavior (for example: flying and landing). To model that, we create a TypeScript class that serves as a blueprint for duck objects. The example below shows a PondDuck class that encapsulates properties (state) and methods (behavior) for each duck instance.
This class demonstrates encapsulation: state (properties) and behavior (methods) are grouped together so each instance manages its own state and transitions. Next, create instances and invoke the methods to see how state changes per instance.
Expected console output:
Each instance (daffy, donald) maintains independent state — calling daffy.fly() does not change donald. The favoriteFood?: string uses TypeScript’s optional property syntax so the constructor can omit it.
Properties and methods at a glance: Key takeaways:
  • Use classes to encapsulate related state and behavior.
  • Optional properties use the ? operator and can be omitted during construction.
  • Methods should manage state transitions (e.g., fly()/land() check isFlying before changing it).
  • Instances are independent; operations on one instance do not affect others.
Links and references:

Watch Video