Introduction to Simple Data Structures in TypeScript

Welcome! Are you ready to dive deep into simple data structures using TypeScript? To aid our journey, we'll explore the utility of TypeScript's Map, a key-value pair data structure that caters to a diverse range of data types.

Exploring TypeScript Maps

A TypeScript Map is an efficient repository of unique key-value pairs, mirroring JavaScript's Map feature. However, TypeScript enhances this feature by enforcing types for keys and values.

Generics in TypeScript are used to create a Map to specify the types of keys and values it will hold, ensuring type safety. This way, the compiler can check that all keys and values added to the map are of the correct type.

Here's how we create and populate a Map in TypeScript:

let planets = new Map<string, string>();  // Initialize a new Map with string types for both keys and values
planets.set('Earth', 'Blue Planet'); // Add entries to the map
planets.set('Mars', 'Red Planet');

console.log(planets); // Logs: Map(2) {"Earth" => "Blue Planet", "Mars" => "Red Planet"}
Enhancing Flexibility with Union Types

In real-world scenarios, you might need a Map to be more flexible. For instance, what if some celestial bodies are identified by their name (a string) and others by a catalog ID (a number)?

In TypeScript, you can use Union Types with the pipe (|) symbol to allow multiple types for keys or values:

// This Map accepts either a string OR a number as a key
let cosmicRegistry = new Map<string | number, string>();

cosmicRegistry.set('Saturn', 'Ringed Planet'); // String key
cosmicRegistry.set(101, 'Unknown Asteroid');   // Number key

console.log(cosmicRegistry.get(101)); // Logs: Unknown Asteroid

Using union types like string | number allows you to handle diverse data while still maintaining strict type safety over which types are allowed.

Utilizing Built-In Map Methods

In addition to the set method seen earlier, Maps in TypeScript offer a host of essential methods such as get, delete, and the has method, all serving as proof of a robust data management system.

console.log(planets.get('Earth')); // Logs: Blue Planet
console.log(planets.has('Mars')); // Logs: true
planets.delete('Mars'); // Deletes the 'Mars' entry from our Map
console.log(planets.has('Mars')); // Logs: false
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal