Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Typescript type definitions for most of Racer's Model API #2

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

ericyhwang
Copy link

⚠️ This is a public PR, so do not discuss internal code or projects here.


This adds a TypeScript type definition file that covers most of Racer's public Model API. These require TypeScript >= 3.4.

To test these definitions out against this PR's branch:

npm install lever/racer#typescript --no-save

For usage examples, see the new tests:
https://github.com/lever/racer/blob/6133d0cf7617b5669829ef9f903891a6dfb5ff0b/test/types-test.ts

Supported and unsupported features

Supported features in this initial set of type definitions:

  • Getter methods
  • Most mutator methods
  • Path and context methods
  • Fetch, subscribe
  • Queries

These features are not included in these initial type definitions:

  • Reactive functions, e.g. Model#start
  • References, e.g. Model#ref
  • Events, e.g.Model#on
  • Filters and sorts, e.g. Model#filter

Implementation notes

Static typing of model data:

  • Each Model<T> has a generic type parameter that should be the type of the data stored at that model's path. Unfortunately, getter and mutator methods don't have data-based type safety, since subpaths are passed in as dot-separated strings.
  • Earlier, I did try a version of the definitions with data-based type checking by changing to path arrays, but TypeScript 3.5 broke those by starting to enforce limits on recursive type evaluations.

ReadonlyDeep:

  • Many of Racer's methods return references to the JS objects stored on its internal root model.data. Such return values should not be directly modified, so these type definitions return ReadonlyDeep versions of types where appropriate, which disallow object property assignments and Array mutations.
  • Some existing code might inappropriately modify such return values, and that should be fixed when converting that code over to TypeScript. Racer has Model#getDeepCopy for returning a recursively deep-copied value, or you can manually do shallow copies where appropriate, e.g. via Object.assign({}, value) for an object or array.slice() for an array.

lib/index.d.ts Outdated Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants