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

Chain custom runtimes with other runtypes #101

Open
sbley opened this issue Jul 22, 2024 · 2 comments
Open

Chain custom runtimes with other runtypes #101

sbley opened this issue Jul 22, 2024 · 2 comments

Comments

@sbley
Copy link

sbley commented Jul 22, 2024

How can I use custom runtimes (that transform a value into another type) with other runtypes?

For example, if I wanted to verify an optional BigInt type:

st.optional(bigIntRuntype()) // 🛑

This would fail because bigIntRuntype() returns bigint whereas st.optional() expects Runtype<unknown> as a parameter.

With the built-in runtypes, it works. Example:

st.optional(stringAsInteger()) // ✅
@hoeck
Copy link
Owner

hoeck commented Jul 22, 2024

The trick is to wrap your bigIntRuntype function with the runtype constructor.

Using plain functions that throw errors is too slow. So simple-runtypes internal return type is a wrapped value. runtype allows you to construct functions that follow that pattern.

Have you tried the example from the README? It shows how to implement a basic BigInt runtype.

@sbley
Copy link
Author

sbley commented Jul 23, 2024

Got it, thank you.

In case it helps anyone, here is a runtype for a base64 check:

export const base64 = <T>(rt: Runtype<T>): Runtype<T> =>
  runtype((v) => {
    // check if base64 encoded string and decode
    const base64Check = use(base64Runtype, v);

    if (base64Check.ok) {
      const internalRuntypeCheck = use(rt, base64Check.result);
      if (internalRuntypeCheck.ok) {
        return internalRuntypeCheck.result;
      }

      return internalRuntypeCheck.error;
    }

    return createError('Invalid base64 string');
  });

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

2 participants