Wondering what’s next for npm?Check out our public roadmap! »

ts-micro-dictTypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

ts-micro-dict

npm version CircleCI codecov Type Coverage Dependency Status devDependencies Status npm

Functions for representing plain objects as typesafe immutable dictionaries

Getting started

$ npm install ts-micro-dict --save

Usage

import { Dict } from 'ts-micro-dict'
 
// explicitly initialize a Dict with plain object
const initial: Dict<number> = { key: 1 }
// or infer entry value type with create function
const alt = Dict.create({ key: 1 })
 
console.log(initial) // { key: 1 }
console.log(alt) // { key: 1 }
 
// immutability
// ERROR - Index signature in type 'Dict<number>' only permits reading:
initial['test'] = 123
// ERROR - Index signature in type 'Dict<number>' only permits reading:
delete initial['key']
 
// type safety
// ERROR - Type 'number | undefined' is not assignable to type 'number':
const x: number = initial['test']
// OK:
const y: number | undefined = initial['test']
 
// create another Dict by adding an entry to existing Dict
const another = Dict.put(initial, 'test', 123)
 
console.log(another) // { key: 1, test: 123 }
console.log(initial) // { key: 1 }
 
// create new Dict by removing an entry from existing Dict
const newDict = Dict.omit(another, 'key')
 
console.log(newDict) // { test: 123 }
console.log(another) // { key: 1, test: 123 }
 
// converting Dict to readonly array
const arr = Dict.toArray(another)
 
console.log(arr) // [['key', 1], ['test', 123]]
 
// entries with undefined values will be removed from toArray result
const oops = Dict.create({ key: 1, oops: undefined, test: 123 })
 
console.log(Dict.toArray(oops)) // [['key', 1], ['test', 123]]
 
// dict, previously converted to array, can be converted back with fromArray
console.log(Dict.fromArray(Dict.toArray(oops))) // { key: 1, test: 123 }
 
// filter
console.log(Dict.filter(oops, x => x > 10)) // { test: 123 }
 
// map
console.log(Dict.map(oops, x => `${x}`)) // { key: '1', test: '123' }

Install

npm i ts-micro-dict

DownloadsWeekly Downloads

34

Version

2.1.0

License

MIT

Unpacked Size

19.8 kB

Total Files

10

Last publish

Collaborators

  • avatar