logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Unleashing the Power of TypeScript

author
Generated by

04/12/2024

typescript

Sign in to read full article

Introduction to TypeScript Classes

TypeScript, a superset of JavaScript, brings static typing and object-oriented programming features to the table. One of its most powerful features is the ability to define and work with classes. Let's explore how classes in TypeScript can help you write more organized and maintainable code.

Basic Class Structure

Here's a simple example of a TypeScript class:

class Car { make: string; model: string; year: number; constructor(make: string, model: string, year: number) { this.make = make; this.model = model; this.year = year; } displayInfo(): string { return `${this.year} ${this.make} ${this.model}`; } } const myCar = new Car("Toyota", "Corolla", 2022); console.log(myCar.displayInfo()); // Output: 2022 Toyota Corolla

In this example, we've defined a Car class with properties and methods. The constructor method initializes the object's properties when a new instance is created.

Access Modifiers

TypeScript provides access modifiers to control the visibility of class members:

  • public: Accessible from anywhere (default)
  • private: Only accessible within the class
  • protected: Accessible within the class and its subclasses

Let's modify our Car class to use access modifiers:

class Car { private make: string; private model: string; private year: number; constructor(make: string, model: string, year: number) { this.make = make; this.model = model; this.year = year; } public displayInfo(): string { return `${this.year} ${this.make} ${this.model}`; } }

Now, the properties are only accessible within the class, while the displayInfo method remains public.

Generics in Classes

Generics allow you to create reusable components that can work with a variety of types. Let's explore how to use generics in classes to create more flexible and type-safe code.

Basic Generic Class

Here's an example of a generic class:

class Box<T> { private content: T; constructor(value: T) { this.content = value; } getValue(): T { return this.content; } } const numberBox = new Box<number>(42); console.log(numberBox.getValue()); // Output: 42 const stringBox = new Box<string>("Hello, TypeScript!"); console.log(stringBox.getValue()); // Output: Hello, TypeScript!

In this example, the Box class can hold any type of value. The type parameter T is specified when creating an instance of the class.

Multiple Type Parameters

You can use multiple type parameters in a generic class:

class Pair<T, U> { constructor(public first: T, public second: U) {} swap(): Pair<U, T> { return new Pair(this.second, this.first); } } const pair = new Pair<string, number>("TypeScript", 4); console.log(pair.first, pair.second); // Output: TypeScript 4 const swappedPair = pair.swap(); console.log(swappedPair.first, swappedPair.second); // Output: 4 TypeScript

This Pair class can hold two values of different types and provides a method to swap their positions.

Generic Constraints

You can use constraints to limit the types that can be used with your generic class:

interface Lengthwise { length: number; } class LengthChecker<T extends Lengthwise> { checkLength(value: T): string { if (value.length > 5) { return "Long"; } else { return "Short"; } } } const stringChecker = new LengthChecker<string>(); console.log(stringChecker.checkLength("TypeScript")); // Output: Long const arrayChecker = new LengthChecker<number[]>(); console.log(arrayChecker.checkLength([1, 2, 3])); // Output: Short

In this example, the LengthChecker class can only work with types that have a length property.

Conclusion

TypeScript classes and generics provide powerful tools for building robust and flexible applications. By leveraging these features, you can create more maintainable and type-safe code. As you continue to explore TypeScript, you'll discover even more ways to enhance your development workflow and improve the quality of your projects.

Popular Tags

typescriptclassesgenerics

Share now!

Like & Bookmark!

Related Collections

  • TypeScript Mastery: From Basics to Advanced

    17/10/2024 | TypeScript

Related Articles

  • Understanding Classes in TypeScript

    17/10/2024 | TypeScript

  • Unleashing the Power of TypeScript

    04/12/2024 | TypeScript

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design