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

Improve type robustness for TrackedAsyncData<T> #2

Merged
merged 1 commit into from
Mar 27, 2021
Merged

Conversation

chriskrycho
Copy link
Collaborator

@chriskrycho chriskrycho commented Mar 27, 2021

Export a union type as the actual public API of TrackedAsyncData<T>, along with a const-bound export of the class (with a safe cast for the constructor). The union is implemented as a union of interfaces which extend the base class so that (a) they are guaranteed to be structurally compatible and (b) docstrings continue to "just work".

The upshot of this change: All existing invocations continue to work exactly as they have up to this point, but the type now correctly narrows when checking any of the boolean properties exposed to indicate the state of the type. For example, given a TrackedAsyncData<string>, the .value and .error properties will have the type null when .isPending is true; .value will have the type string when .isResolved is true but .error will still be null, etc.


Thanks to @dfreeman for suggesting a variant on this approach!

Export a union type as the actual public API of `TrackedAsyncData<T>`,
along with a `const`-bound export of the class (with a safe cast for the
constructor). The union is implemented as a union of interfaces which
extend the base class so that (a) they are guaranteed to be structurally
compatible and (b) docstrings continue to "just work".

The upshot of this change: All existing invocations continue to work
exactly as they have up to this point, but the type now correctly
narrows when checking any of the boolean properties exposed to indicate
the state of the type. For example, given a `TrackedAsyncData<string>`,
the `.value` and `.error` properties will have the type `null` when
`.isPending` is `true`; `.value` will have the type `string` when
`.isResolved` is `true` but `.error` will still be `null`, etc.
@chriskrycho chriskrycho merged commit 0545a5c into main Mar 27, 2021
@delete-merged-branch delete-merged-branch bot deleted the better-types branch March 27, 2021 21:17
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.

None yet

1 participant