TypeScript Collections
typescript-collections is a robust and fully tested data structure library written in TypeScript, currently at version 1.3.3. It provides a comprehensive suite of common data structures, including Linked Lists, Dictionaries (regular, multi, and default), Binary Search Trees, Stacks, Queues, Sets, Bags, Binary Heaps, and Priority Queues, alongside array utility functions. The library leverages TypeScript Generics to offer strong type safety and enhanced developer experience through IntelliSense. It supports UMD (Universal Module Definition), making it suitable for use in Node.js, modern browsers, and other JavaScript environments. A key design aspect for its hashing-based collections (like `Dictionary` and `Set`) is the reliance on an item's `toString()` method for equality checks, necessitating custom implementations for non-primitive keys to ensure correct behavior. The package was last published 6 years ago, suggesting it is in a maintenance phase with infrequent updates.
Common errors
-
Argument of type 'string' is not assignable to parameter of type 'number'.
cause Attempting to add an element of a type that does not match the generic type argument specified for the collection (e.g., adding a `string` to a `Set<number>`).fixEnsure the type of the element being added/inserted/queued matches the generic type argument of the collection instance. For example, if `mySet` is `Set<number>`, only add `number` values. -
Cannot find module 'typescript-collections' or its corresponding type declarations.
cause The TypeScript compiler is unable to locate the package or its type definitions. Common reasons include missing `"moduleResolution": "node"` in `tsconfig.json`, incorrect installation, or an invalid import path.fixVerify `typescript-collections` is installed (`npm install typescript-collections`). Check `tsconfig.json` for `"compilerOptions": { "moduleResolution": "node" }`. Ensure the import statement is `import * as Collections from 'typescript-collections';`. -
Object equality for custom types not working as expected in collections like `Dictionary` or `Set`.
cause `typescript-collections` uses the `toString()` method for object equality checks in hashing-based collections. If custom objects do not have a meaningful `toString()` implementation, they may be treated as unequal even if their contents are the same, or vice versa.fixImplement a `toString()` method on your custom object classes that returns a unique string representation for distinct objects and an identical string for equal objects. Example: `class MyKey { id: string; toString() { return this.id; } }`.
Warnings
- gotcha For hashing-based collections like `Dictionary` and `Set`, `typescript-collections` relies on the `toString()` method of objects for equality and uniqueness checks. If you use custom objects as keys or values in these collections, you *must* implement a `toString()` method that provides a unique and consistent string representation for equal objects. Otherwise, behavior may be incorrect (e.g., duplicates being added, or `contains` failing).
- gotcha To ensure TypeScript properly resolves the type definitions, particularly in older or non-standard configurations, you may need to explicitly set `"moduleResolution": "node"` in your `tsconfig.json`'s `compilerOptions`.
- gotcha When using `typescript-collections` directly in a browser environment without a bundler, you must manually include the UMD bundle. This is typically `dist/lib/umd.min.js` (or `umd.js`).
- breaking `typescript-collections` explicitly requires TypeScript 0.9 or above due to its reliance on TypeScript Generics. Older TypeScript versions are not supported.
Install
-
npm install typescript-collections -
yarn add typescript-collections -
pnpm add typescript-collections
Imports
- Collections
import * as Collections from 'typescript-collections';
- Collections
import * as Collections from 'typescript-collections';
import Collections = require('typescript-collections'); - Collections
import Collections from 'typescript-collections';
var Collections = require('typescript-collections'); - util.makeString
import * as Collections from 'typescript-collections'; const str = Collections.util.makeString(myObject);
Quickstart
import * as Collections from 'typescript-collections';
// Demonstrate Set usage with generics for type safety
var mySet = new Collections.Set<number>();
mySet.add(123);
mySet.add(456);
mySet.add(123); // Duplicate, will not be added to the set
console.log(`Set size: ${mySet.size()}`); // Expected output: Set size: 2
console.log(`Set contains 456: ${mySet.contains(456)}`); // Expected output: Set contains 456: true
// Demonstrate Queue usage
var myQueue = new Collections.Queue<string>();
myQueue.enqueue("first");
myQueue.enqueue("second");
console.log(`Dequeued: ${myQueue.dequeue()}`); // Expected output: Dequeued: first
console.log(`Dequeued: ${myQueue.dequeue()}`); // Expected output: Dequeued: second
console.log(`Queue is empty: ${myQueue.isEmpty()}`); // Expected output: Queue is empty: true
// Example of custom object as a key in a Dictionary, requiring custom toString()
class User {
constructor(public id: number, public name: string) {}
toString() { // Crucial for correct hashing behavior in Collections.Dictionary/Set
return `User-${this.id}`;
}
}
const userDict = new Collections.Dictionary<User, string>();
const user1 = new User(1, "Alice");
const user2 = new User(2, "Bob");
userDict.setValue(user1, "Administrator");
userDict.setValue(user2, "Guest");
console.log(`User 1 role: ${userDict.getValue(user1)}`); // Expected output: User 1 role: Administrator