node-open-protocol icon indicating copy to clipboard operation
node-open-protocol copied to clipboard

Typed constants

Open ferm10n opened this issue 3 years ago • 0 comments

What

  • convert json consts to js, and add type defs for them

Why

This is useful for dependent projects that want type safety. For example:

import midGroups from 'node-open-protocol/typings/src/midGroups';
type MidGroups = typeof midGroups;

// filter out the mid groups that don't have `subscribe`
type Subscribable = {
  [ midGroup in keyof MidGroups ]: MidGroups[midGroup] extends { subscribe: number } ? MidGroups[midGroup] : never;
}

// only valid subscription mid group names would be allowed
const cmd: keyof Subscribable = 'psetSelected';

// only valid subscription mid ids would be allowed
const subscribeMid: Subscribable[keyof Subscribable] = midGroups.psetSelected.subscribe;

Rationale

  • there's no way to import a json as a const type (where subscribe is stricter than number) so thats why the convert to js (see https://github.com/microsoft/TypeScript/issues/32063)

ferm10n avatar Jun 02 '22 20:06 ferm10n