CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-better-typescript-lib

An alternative TypeScript standard library with better type definitions

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

es2015-features.mddocs/

ES2015+ Features

Enhanced type definitions for modern JavaScript features including Promises, Collections, Iterables, Symbols, and other ES2015+ capabilities with improved type safety.

Capabilities

Promise Enhancements

Improved Promise interface with better type safety and method signatures.

interface Promise<T> {
  /**
   * Attaches callbacks for the resolution and/or rejection of the Promise.
   * Enhanced with better null/undefined handling.
   */
  then<TResult1 = T, TResult2 = never>(
    onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,
    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined
  ): Promise<TResult1 | TResult2>;

  /**
   * Attaches a callback for only the rejection of the Promise.
   * Enhanced with better null/undefined handling.
   */
  catch<TResult = never>(
    onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined
  ): Promise<T | TResult>;

  /**
   * Attaches a callback that is invoked when the Promise is settled.
   */
  finally(onfinally?: (() => void) | null | undefined): Promise<T>;
}

interface PromiseConstructor {
  /**
   * Creates a Promise that is resolved with an array of results when all provided Promises resolve.
   */
  all<T extends readonly unknown[] | []>(values: T): Promise<{
    -readonly [P in keyof T]: Awaited<T[P]>;
  }>;

  /**
   * Creates a Promise that resolves when any of the provided Promises resolves.
   */
  race<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>;

  /**
   * Creates a Promise that resolves to the provided value.
   */
  resolve(): Promise<void>;
  resolve<T>(value: T | PromiseLike<T>): Promise<T>;

  /**
   * Creates a Promise that rejects with the provided reason.
   */
  reject<T = never>(reason?: any): Promise<T>;
}

Usage Examples:

// Enhanced Promise chaining with better null handling
async function fetchUserProfile(userId: string) {
  return fetch(`/api/users/${userId}`)
    .then(response => response.json()) // Returns JSONValue
    .then(data => {
      if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
        return data;
      }
      throw new Error('Invalid user data');
    })
    .catch(error => {
      console.error('Failed to fetch user:', error);
      return null; // Explicit null return
    });
}

// Promise.all with improved type inference
async function fetchMultipleResources() {
  const [users, posts, comments] = await Promise.all([
    fetch('/api/users').then(r => r.json()),
    fetch('/api/posts').then(r => r.json()),
    fetch('/api/comments').then(r => r.json())
  ]);
  // Each result is properly typed as JSONValue
  
  return { users, posts, comments };
}

Collection Types (Map, Set)

Enhanced Map and Set interfaces with improved type safety.

interface Map<K, V> {
  /**
   * Removes all elements from the Map.
   */
  clear(): void;
  
  /**
   * Removes a specified element from the Map.
   */
  delete(key: K): boolean;
  
  /**
   * Executes a callback function once per key/value pair.
   */
  forEach(
    callbackfn: (value: V, key: K, map: Map<K, V>) => void,
    thisArg?: any
  ): void;
  
  /**
   * Returns a specified element from the Map.
   */
  get(key: K): V | undefined;
  
  /**
   * Returns a boolean indicating whether an element exists.
   */
  has(key: K): boolean;
  
  /**
   * Adds a new element with a specified key and value.
   */
  set(key: K, value: V): this;
  
  /**
   * Returns the number of elements in the Map.
   */
  readonly size: number;
  
  /**
   * Returns an iterable of entries.
   */
  entries(): IterableIterator<[K, V]>;
  
  /**
   * Returns an iterable of keys.
   */
  keys(): IterableIterator<K>;
  
  /**
   * Returns an iterable of values.
   */
  values(): IterableIterator<V>;
  
  [Symbol.iterator](): IterableIterator<[K, V]>;
}

interface Set<T> {
  /**
   * Appends a new element to the Set.
   */
  add(value: T): this;
  
  /**
   * Removes all elements from the Set.
   */
  clear(): void;
  
  /**
   * Removes a specified value from the Set.
   */
  delete(value: T): boolean;
  
  /**
   * Executes a callback function once per value.
   */
  forEach(
    callbackfn: (value: T, value2: T, set: Set<T>) => void,
    thisArg?: any
  ): void;
  
  /**
   * Returns a boolean indicating whether an element exists.
   */
  has(value: T): boolean;
  
  /**
   * Returns the number of elements in the Set.
   */
  readonly size: number;
  
  /**
   * Returns an iterable of entries.
   */
  entries(): IterableIterator<[T, T]>;
  
  /**
   * Returns an iterable of values.
   */
  keys(): IterableIterator<T>;
  values(): IterableIterator<T>;
  
  [Symbol.iterator](): IterableIterator<T>;
}

Usage Examples:

// Type-safe Map operations
const userCache = new Map<string, JSONValue>();
userCache.set('user1', { name: 'Alice', age: 30 });
userCache.set('user2', { name: 'Bob', age: 25 });

// Safe retrieval with type checking
function getUser(id: string): { name: string; age: number } | null {
  const userData = userCache.get(id);
  if (userData && typeof userData === 'object' && !Array.isArray(userData)) {
    const name = userData.name;
    const age = userData.age;
    if (typeof name === 'string' && typeof age === 'number') {
      return { name, age };
    }
  }
  return null;
}

// Set operations with type safety
const uniqueIds = new Set<string>();
uniqueIds.add('abc123');
uniqueIds.add('def456');

// Iteration with proper types
for (const id of uniqueIds) {
  console.log(`Processing ID: ${id}`); // id is properly typed as string
}

Symbol Enhancements

Enhanced Symbol interface and well-known symbols.

interface Symbol {
  /**
   * Returns a string representation of the symbol.
   */
  toString(): string;
  
  /**
   * Returns the primitive value of the symbol.
   */
  valueOf(): symbol;
  
  /**
   * Returns a string description of the symbol.
   */
  readonly description: string | undefined;
}

interface SymbolConstructor {
  /**
   * Returns a new unique Symbol value.
   */
  (description?: string | number): symbol;
  
  /**
   * Returns a Symbol value from the global symbol registry.
   */
  for(key: string): symbol;
  
  /**
   * Returns the key for a symbol from the global symbol registry.
   */
  keyFor(sym: symbol): string | undefined;
  
  // Well-known symbols
  readonly iterator: unique symbol;
  readonly asyncIterator: unique symbol;
  readonly hasInstance: unique symbol;
  readonly isConcatSpreadable: unique symbol;
  readonly species: unique symbol;
  readonly toPrimitive: unique symbol;
  readonly toStringTag: unique symbol;
}

Iterator Interfaces

Enhanced iterator and iterable interfaces.

interface Iterator<T, TReturn = any, TNext = undefined> {
  next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
  return?(value?: TReturn): IteratorResult<T, TReturn>;
  throw?(e?: any): IteratorResult<T, TReturn>;
}

interface IteratorResult<T, TReturn = any> {
  done: boolean;
  value: T | TReturn;
}

interface Iterable<T> {
  [Symbol.iterator](): Iterator<T>;
}

interface IterableIterator<T> extends Iterator<T> {
  [Symbol.iterator](): IterableIterator<T>;
}

Usage Examples:

// Working with symbols
const idSymbol = Symbol('id');
const userSymbol = Symbol.for('currentUser');

// Using symbols as object keys
const obj = {
  [idSymbol]: 'user123',
  name: 'Alice'
};

// Symbol iteration
function* numberGenerator(): Generator<number> {
  let i = 0;
  while (i < 5) {
    yield i++;
  }
}

const numbers = numberGenerator();
for (const num of numbers) {
  console.log(num); // num is properly typed as number
}

// Custom iterable
class NumberRange implements Iterable<number> {
  constructor(private start: number, private end: number) {}
  
  *[Symbol.iterator](): Iterator<number> {
    for (let i = this.start; i <= this.end; i++) {
      yield i;
    }
  }
}

const range = new NumberRange(1, 5);
for (const num of range) {
  console.log(num); // Type-safe iteration
}

Reflect API Enhancements

Enhanced Reflect API with improved type safety.

interface Reflect {
  /**
   * Calls a target function with arguments as specified by the args parameter.
   */
  apply<T, A extends readonly any[], R>(
    target: (this: T, ...args: A) => R,
    thisArgument: T,
    argumentsList: Readonly<A>
  ): R;
  
  /**
   * The new operator as a function.
   */
  construct<A extends readonly any[], R>(
    target: new (...args: A) => R,
    argumentsList: Readonly<A>,
    newTarget?: any
  ): R;
  
  /**
   * Defines a property on an object.
   */
  defineProperty(
    target: object,
    propertyKey: PropertyKey,
    attributes: PropertyDescriptor
  ): boolean;
  
  /**
   * Deletes a property from an object.
   */
  deleteProperty(target: object, propertyKey: PropertyKey): boolean;
  
  /**
   * Gets a property value.
   */
  get(target: object, propertyKey: PropertyKey, receiver?: any): any;
  
  /**
   * Determines whether an object has a property.
   */
  has(target: object, propertyKey: PropertyKey): boolean;
  
  /**
   * Sets a property value.
   */
  set(
    target: object,
    propertyKey: PropertyKey,
    value: any,
    receiver?: any
  ): boolean;
}

docs

dom-enhancements.md

es5-core.md

es2015-features.md

index.md

json-types.md

typed-arrays.md

tile.json