Wednesday, July 26, 2017

maps in TypeScript (think dictionary)

What follows is stolen from here and I don't really know if it is quite exactly an example of a Map or a WeakMap as of yet. Assume this is a public variable in an Angular 2 component:

public fileMap: {[key:number]: any};

 
 

Add stuff like this:

addItem(id:number, file:any): void {
   if (!this.fileMap) this.fileMap = {};
   this.fileMap[id] = file;
}

 
 

Get stuff back out like this:

getFileThirteen(): void {
   if (!this.fileMap) this.fileMap = {};
   let fileThirteen = this.fileMap[13];
   return fileThirteen;
}

 
 

If item 13 isn't there, undefined will be returned above.

No comments:

Post a Comment