Skip to content

Conversation

@mattpocock
Copy link
Contributor

@mattpocock mattpocock commented Aug 18, 2024

I would like err to infer strings more narrowly. This would make it easier to create unions out of possible string errors.

const example = (num: number) => {
  if (num < 0) return err('Too low');
  if (num > 100) return err('Too high');

  return ok(num);
}

This would infer as Ok<number> | Err<'Too low'> | Err<'Too high'>.

Let me know if this is desirable.

@changeset-bot
Copy link

changeset-bot bot commented Aug 18, 2024

🦋 Changeset detected

Latest commit: eadf50c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
neverthrow Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

export const ok = <T, E = never>(value: T): Ok<T, E> => new Ok(value)

export const err = <T = never, E = unknown>(err: E): Err<T, E> => new Err(err)
export function err<T = never, E extends string = string>(err: E): Err<T, E>
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Can do this with an overloaded type if you'd prefer, but figured this was the easiest way to make this change.

});
});

(function describe(_ = 'err') {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Wasn't sure where this test should go, so made its own block.


const assignableToCheck: Expectation = result;
});
})
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Side note - prettier can't run on this file because it's an outdated version and there's an 'import type'.

When I did try to run prettier on it, a LOT of changes were made, probably to do with the semicolons.

Copy link
Owner

Choose a reason for hiding this comment

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

@m-shaka mentioned we may want to use biome instead of prettier, but perhaps if we just update prettier this issue goes away?

@supermacro supermacro merged commit 2e25831 into supermacro:master Aug 19, 2024
@supermacro
Copy link
Owner

Thanks for the contribution @mattpocock :)

@macksal
Copy link
Contributor

macksal commented Sep 19, 2024

Just found this in the blame while working on #584. Nice work @mattpocock. It might be useful for ok/okAsync/errAsync to have the same overload.

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.

3 participants