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 specificity of return type #49

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

nickiaconis
Copy link
Contributor

Increases the specificity of the return type. This allows consumers to make assumptions about the existence of value based on the value/presence of loading and error.

For example, this will produce a type error with the current version of react-promise, but will work as expected with these changes:

function processMessage(input: string): string;

const messagePromise: Promise<string> = doXHRGetString();
const asyncMessage = usePromise(messagePromise);
const displayValue = asyncMessage.loading
  ? 'loading'
  : asyncMessage.error
  ? asyncMessage.error.toString()
  : processMessage(asyncMessage.value); // type error here with current version b/c `value` is type `string | undefined`

@@ -22,7 +28,7 @@ export default function usePromise<T>(
if (!promiseOrFn) {
setState({
loading: false,
error: null,
error: new TypeError(`The argument passed to usePromise must be either a promise or a function, but you passed a ${typeof promiseOrFn}`),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, this could throw a type error instead b/c a falsy value in promiseOrFn doesn't satisfy the type specified for the hook argument. Throwing an error might be better than setting an error on the state since this has the potential to be incorrectly interpreted as a rejected promise. 🤷 Would like your input on this please.

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.

1 participant