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

Advanced Types in TypeScript

author
Generated by
Abhishek Goyan

17/10/2024

TypeScript

Sign in to read full article

TypeScript is a powerful superset of JavaScript that allows developers to add static types to their code, which greatly enhances code readability and maintainability. While many developers are familiar with basic types like string, number, and boolean, TypeScript also offers a variety of advanced types that can significantly improve your coding experience. Let’s take a closer look at these advanced types and how you can use them effectively in your projects.

1. Union Types

Union types allow you to define a variable that can hold values of multiple types. This is particularly useful when a function can accept different types of inputs.

Example:

function printId(id: number | string) { console.log(`Your ID is: ${id}`); } printId(101); // Output: Your ID is: 101 printId('202'); // Output: Your ID is: 202

In this example, the printId function can accept both a number and a string as its argument, providing flexibility in how the function can be called.

2. Intersection Types

Intersection types allow you to combine multiple types into one. This is useful when you want to create a new type that includes properties from multiple existing types.

Example:

interface Person { name: string; } interface Employee { id: number; } type EmployeePerson = Person & Employee; const employee: EmployeePerson = { name: "Jane Doe", id: 123, }; console.log(employee); // Output: { name: "Jane Doe", id: 123 }

Here, the EmployeePerson type combines the Person and Employee types, letting us create an object that satisfies both interfaces.

3. Type Guards

Type guards are special constructs that help you narrow down types within a conditional block. This allows TypeScript to understand what specific type a variable holds, enabling better type checking.

Example:

function processValue(value: number | string) { if (typeof value === "string") { console.log(`String value: ${value.toUpperCase()}`); } else { console.log(`Numeric value: ${value.toFixed(2)}`); } } processValue(10); // Output: Numeric value: 10.00 processValue("hello"); // Output: String value: HELLO

The processValue function uses the typeof operator as a type guard to differentiate between string and number types, ensuring appropriate operations are performed based on the type of value.

4. Conditional Types

Conditional types enable you to create types that depend on a condition. This is similar to a ternary operator for types and can be incredibly powerful for advanced type manipulation.

Example:

type IsString<T> = T extends string ? "This is a string" : "This is not a string"; type Check1 = IsString<string>; // Check1 is "This is a string" type Check2 = IsString<number>; // Check2 is "This is not a string"

In this example, the type IsString evaluates whether the type T is a string or not, allowing the creation of types based on conditions.

5. Mapped Types

Mapped types let you create new types by transforming properties of an existing type. This is useful for creating variations of existing types without duplicating code.

Example:

type User = { name: string; age: number; }; type ReadonlyUser = { readonly [K in keyof User]: User[K]; }; const user: ReadonlyUser = { name: "Alice", age: 30, }; // user.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property

Here, ReadonlyUser is a new type that makes all properties of the original User type read-only.

6. Template Literal Types

Template literal types are a recent addition to TypeScript that allows you to create types using string literals. This feature is great for creating structured string-based types.

Example:

type EventType = "click" | "hover" | "submit"; type EventListener<K extends EventType> = `${K}Listener`; let clickListener: EventListener<"click"> = "clickListener"; // Valid let hoverListener: EventListener<"hover"> = "hoverListener"; // Valid // let invalidListener: EventListener<"click"> = "blurListener"; // Error: Type '"blurListener"' is not assignable

In this example, EventListener generates a new type based on the provided event type, demonstrating how you can use template literals for type generation.

By leveraging these advanced types, you can take full advantage of TypeScript's capabilities, creating more dynamic and type-safe code. Whether you are building a large-scale application or maintaining a small project, understanding these advanced types is key to writing code that is both efficient and easy to maintain. Explore these types further, experiment, and watch as TypeScript elevates your programming experience!

Popular Tags

TypeScriptAdvanced TypesType System

Share now!

Like & Bookmark!

Related Collections

  • TypeScript Mastery: From Basics to Advanced

    17/10/2024 | TypeScript

Related Articles

  • Harnessing the Power of TypeScript with Node.js

    17/10/2024 | TypeScript

  • Understanding Basic Types in TypeScript

    17/10/2024 | TypeScript

  • Setting Up TypeScript

    17/10/2024 | TypeScript

  • Understanding Type Guards in TypeScript

    17/10/2024 | TypeScript

  • Unit Testing with TypeScript

    17/10/2024 | TypeScript

  • TypeScript with React

    17/10/2024 | TypeScript

  • Understanding Classes in TypeScript

    17/10/2024 | TypeScript

Popular Category

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