Code Monkey home page Code Monkey logo

Comments (13)

marlonjan avatar marlonjan commented on August 17, 2024 8

If you want to (or have to) keep the enum, this snippet might be useful:

import * as rt from 'runtypes';

const runtypeFromEnum = <EnumType>(theEnum: Record<string, EnumType>): rt.Runtype<EnumType> => {
    const values = Object.values<unknown>(theEnum);
    const isEnumValue = (input: unknown): input is EnumType => values.includes(input);
    const errorMessage = (input: unknown): string =>
        `Failed constraint check. Expected one of ${JSON.stringify(values)}, but received ${JSON.stringify(input)}`;
    return rt.Unknown.withConstraint<EnumType>((object: any) => isEnumValue(object) || errorMessage(object));
};

Usage:

enum Parser {
    STANDARD = 'standard',
    FIVE_FILTERS = 'fiveFilters',
}

const ParserRuntype = runtypeFromEnum(Parser);

const p1: Parser = ParserRuntype.check(Parser.STANDARD); // ok
const p2: Parser = ParserRuntype.check('standard');      // ok
const p3: Parser = ParserRuntype.check('standarddd');    // error

(Inspired by @pelotom's replies here and answers to a very similar question in the io-ts issues.)

from runtypes.

pelotom avatar pelotom commented on August 17, 2024 2

There's a feature in the works to make Constraint able to change the static type associated with a runtype. Just needs documentation and it will be ready to merge (nudge @justingrant).

If you happen to have a type guard already that validates your custom type, e.g.

function isMyCustomType(x: any): x is MyCustomType;

then you'll be able to write

// MyCustomRuntype: Runtype<MyCustomType>
const MyCustomRuntype = Unknown.withGuard(isMyCustomType);

from runtypes.

xavichoudev avatar xavichoudev commented on August 17, 2024 2

For parser I would use

Union(
    Literal(Parser.STANDARD),
    Literal(Parser.FIVE_FILTERS)
  )

Is there a way to create that Union programmatically based on the entries in the enum? As if you update the enum and forget to update the Union..

Warning Union seems to be limited to max 20 elements.

from runtypes.

tvald avatar tvald commented on August 17, 2024 1

Actually, this is possible right now with a very reasonable syntax:

const complex = Unknown as Runtype<Complex>;

The "light" validator runtype might still be an interesting path to enable some modicum of runtime safety.

from runtypes.

hmil avatar hmil commented on August 17, 2024

I would leave admin.firestore.DocumentReference as an Unknown unless you know what's inside this type and you are able to easily map it to a runtype of your own.
Then I'd treat the enums like string unions (eg. parser: Union(String('standard'), String('fiveFilters')))

from runtypes.

tvald avatar tvald commented on August 17, 2024

For a complex external type Complex, perhaps a new runtype Unsafe could be added that always validates, just like Unknown, but also asserts for the compiler that the type is Complex.

const complex = Unsafe<Complex>();
// Static<typeof complex> === Complex

This at least enables the compiler to check the type wherever possible, and should be no more unsafe than the type assertion required to use a value validated by Unknown.

It might also be worth accepting a "light" validator function as a parameter:

const readableStream = Unsafe<NodeJS.ReadableStream>(x => 'read' in x);

from runtypes.

tvald avatar tvald commented on August 17, 2024

The "light" validator is possible like so:

const complex = Unknown.withConstraint(x => 'foo' in x) as Runtype<Complex>;

from runtypes.

justingrant avatar justingrant commented on August 17, 2024

Sorry @pelotom and @tvald for lagging on this. Will try to get it out next week. Have been knee-deep in other stuff for the last few weeks.

from runtypes.

pelotom avatar pelotom commented on August 17, 2024

@justingrant no worries, just wanted to make sure you knew your work will be appreciated 😉

from runtypes.

pelotom avatar pelotom commented on August 17, 2024

#78 has been merged and released in [email protected], so this should be solved now.

from runtypes.

ronanquillevere avatar ronanquillevere commented on August 17, 2024

For parser I would use

Union(
    Literal(Parser.STANDARD),
    Literal(Parser.FIVE_FILTERS)
  )

from runtypes.

dforsber avatar dforsber commented on August 17, 2024

For parser I would use

Union(
    Literal(Parser.STANDARD),
    Literal(Parser.FIVE_FILTERS)
  )

Is there a way to create that Union programmatically based on the entries in the enum? As if you update the enum and forget to update the Union..

from runtypes.

Mearman avatar Mearman commented on August 17, 2024

@marlonjan I understand the usage but I'm not entirely sure what the value of the input is EnumType is in the declaration of isEnumValue

from runtypes.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.