Level / abstract-level

Abstract class for a lexicographically sorted key-value database.
MIT License
123 stars 8 forks source link

Review TypeScript declaration files #5

Closed vweevers closed 2 years ago

vweevers commented 2 years ago

Disclaimer: I'm not committing to maintaining typings here (rather than DT) and it will not be a blocker for release. I just found them useful when implementing level-transcoder and also wanted to learn something new.

Start here. The main export is AbstractLevel<TFormat, KDefault = string, VDefault = string> with three generic type parameters:

  1. TFormat: the type used by the implementation to store data; see level-transcoder for background
  2. KDefault: the type of keys, if not overridden on individual methods
  3. VDefault: the type of values, if not overridden.

Downstream, for example in memory-level (the replacement for memdown), the types will look like this (simplified):

import { AbstractLevel, AbstractDatabaseOptions } from 'abstract-level'

export class MemoryLevel<KDefault = string, VDefault = string>
  extends AbstractLevel<Buffer | Uint8Array | string, KDefault, VDefault> {
  constructor (
    options?: AbstractDatabaseOptions<KDefault, VDefault> | undefined
  )
}

For a consumer of such an implementation, usage in TypeScript then looks like this:

// Specify types of keys and values (any, in the case of json).
// The generic type parameters default to level<string, string>.
const db = new MemoryLevel<string, any>({ valueEncoding: 'json' })

// All relevant methods then use those types
await db.put('a', { x: 123 })

// Specify different types when overriding encoding per operation
await db.get<string, string>('a', { valueEncoding: 'utf8' })

// Though in some cases TypeScript can infer them
await db.get('a', { valueEncoding: db.valueEncoding('utf8') })

Which I believe to be a fair balance between DX and maintainable (simple) typings. I will push new code and typings to memory-level later; might make it easier to review if you have an actual database to play around with.