Computed properties

Initializing an object with dynamic properties can be a bit of a burden. Take the following example:

  1. type NeighborMap = { [name: string]: Node };
  2. type Node = { name: string; neighbors: NeighborMap;}
  3. function makeNode(name: string, initialNeighbor: Node): Node {
  4. var neighbors: NeighborMap = {};
  5. neighbors[initialNeighbor.name] = initialNeighbor;
  6. return { name: name, neighbors: neighbors };
  7. }

Here we need to create a variable to hold on to the neighbor-map so that we can initialize it. With TypeScript 1.5, we can let the compiler do the heavy lifting:

  1. function makeNode(name: string, initialNeighbor: Node): Node {
  2. return {
  3. name: name,
  4. neighbors: {
  5. [initialNeighbor.name]: initialNeighbor
  6. }
  7. }
  8. }