TypeScript
Dictionary Equivalence

by Benny Neugebauer

import Account from './Account'

class AccountManager {
  private accounts: Map<string, Account>

  constructor() {
    this.accounts = new Map()
  }

  addAccount(account: Account): void {
    this.accounts.set(account.getName(), account)
  }

  getAccount(name: string): Account | undefined {
    return this.accounts.get(name)
  }

  printAccounts(): void {
    for (const account of this.accounts.values()) {
      console.log(account.getName())
    }
  }
}

import Account from './Account'

class AccountManager {
  private accounts: { [index: string]: Account }

  constructor() {
    this.accounts = {}
  }

  addAccount(account: Account): void {
    this.accounts[account.getName()] = account
  }

  getAccount(name: string): Account | undefined {
    return this.accounts[name]
  }

  printAccounts(): void {
    for (const name in this.accounts) {
      const account = this.accounts[name]
      console.log(account.getName())
    }
  }
}

Maps are not part of ES5 and can lead to TypeScript error TS2495: Type 'IterableIterator' is not an array type or a string type. In that case a simple object is preferable.

Benny Neugebauer

Sign in to comment!