TypeScript Map Structure

1.0.3 · active · verified Sun Apr 19

ts-map is a TypeScript library that provides a Map-like data structure, mirroring the functionality of the native ES6 Map object but explicitly designed for TypeScript environments. Its current stable version is 1.0.3, with no specific release cadence indicated beyond that. The library aims to offer a familiar API for key-value pair storage, where keys can be of any type (including objects), not just strings, which is a key differentiator from plain JavaScript objects. It supports generics for strong typing of both keys and values, enhancing type safety in TypeScript projects. While it replicates standard Map methods like `set`, `get`, `has`, `delete`, `clear`, `size`, `keys`, `values`, `entries`, and `forEach`, its primary distinction lies in its explicit TypeScript typing and design, which might appeal to developers looking for a fully typed alternative. It's important to note that object keys are compared by reference, mirroring ES6 Map behavior, which is a common gotcha for developers expecting value-based comparison.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic instantiation, setting various key types, retrieving values, iterating over map entries, and using generics for type safety.

import TsMap from 'ts-map';

// Basic instantiation and usage
const map = new TsMap();
const k1: number = 1;
const k2: number[] = [2]; 
const k3: boolean = true;

map.set(1, "hello");
map.set(k2, "ts").set(k3, "map");

console.log('Get 1:', map.get(1));
console.log('Get k2:', map.get(k2));
console.log('Size:', map.size);
console.log('Keys:', map.keys());
console.log('Values:', map.values());

console.log('-- ForEach --');
map.forEach((value, key) => {
  console.log(key, ':', value);
});

// Constructor with parameter
const initialMap = new TsMap<number, string>([
  [1, "ok"],
  [2, "fail"]
]);
console.log('Initial map get 1:', initialMap.get(1));

// Class generic usage
interface Coder {
  name: string;
}

const typedMap = new TsMap<number, Coder>([
  [1, {name: 'lavyun'}]
]);

typedMap.set(2, {name: "tom"});
// typedMap.set(3, "jack"); // This line would cause a TypeScript error as expected
console.log('Typed map get 1:', typedMap.get(1));

view raw JSON →