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

[Discussion / Feature Request] Inclusion of "assert" in addition to "is" guards #442

Open
Tenga opened this issue Apr 10, 2020 · 0 comments

Comments

@Tenga
Copy link

Tenga commented Apr 10, 2020

Disclaimer: I understand this might at first sound similar to #422, but I do not believe the intent there was the same.

On the Codecs, currently we have the is method which has the type guard signature (v: unknown) => v is X.

Assuming an existing User codec:

const User = t.type({ /* ... */ });

We can currently do:

const x: unknown = { /* ... */ };

if (User.is(o)) {
  // x is t.TypeOf<typeof User> here
}

// x is still unknown here

Now, considering the addition of the (v: unknown) => assert v is X syntax with TS in TS 3.7, I'm thinking/proposing that it might be worthwhile to add a convenience assert method on the Codecs, so the following could be done:

const x: unknown = { /* ... */ };
User.assert(x); // x is t.TypeOf<typeof User> from now on

This is currently manually doable by combining decode and the deprecated ThrowReporter:

function assertIsUser(v: unknown): asserts v is t.TypeOf<typeof User> {
  ThrowReporter.report(User.decode(v))
}

So the benefit here is only convenience, but one could argue that is is convenience as well. 😄

A potential problem here, apart from not wishing to include this convenience in io-ts, is that io-ts currently supports TS 3.5.2+ and the syntax is only introduced in TS 3.7, so library users under that version would potentially encounter errors.

Should the maintainers not wish to force TS 3.7 as a minimum requirement, a solution exists:

Since TS 3.1, typesVersions property in the package.json exists, and io-ts could ship with a set of alternate types where the (v: unknown) => asserts v is X syntax would be in the form of (v: unknown) => void to support those users, without forcing a mandatory version bump.

This type generation could be automated via a build process step with downlevel-dts
once this PR is merged. downlevel-dts seems destined to become officially supported and the part of Microsoft organisation in the near future according to the TS 3.9 iteration plan.

Thank you for your time!

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

No branches or pull requests

1 participant