Comments (13)
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.
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.
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 theUnion
..
Warning Union seems to be limited to max 20 elements.
from runtypes.
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.
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.
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.
The "light" validator is possible like so:
const complex = Unknown.withConstraint(x => 'foo' in x) as Runtype<Complex>;
from runtypes.
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.
@justingrant no worries, just wanted to make sure you knew your work will be appreciated 😉
from runtypes.
#78 has been merged and released in [email protected]
, so this should be solved now.
from runtypes.
For parser I would use
Union(
Literal(Parser.STANDARD),
Literal(Parser.FIVE_FILTERS)
)
from runtypes.
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.
@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)
- Is there a way to omit everything that's not defined by the Record instance? HOT 1
- Create runtypes from existing TypeScript types? HOT 1
- Printable form of type from runtype? HOT 1
- Unuseful error message on typechecking HOT 1
- Cannot validate optional+null circulare fields HOT 4
- Optional types in Tuple HOT 1
- How check for ObjectId? HOT 3
- Function which accepts a runtype and omits some fields HOT 1
- `omit` properties of a `Constraint` or `Intersect`? HOT 2
- Constraint::reflect does not expose .underlying
- Support for Set type HOT 2
- [Feature Request] Type Guard for ValidationError HOT 2
- Option to return errors instead of throwing them for performant validation. HOT 4
- Runtypes-like `.guard()` HOT 1
- How do I exclude undefined properties from record? HOT 2
- Is it possible to have more than one brand HOT 2
- Type validated by Dictionary is different than returned type
- How do I define an array which is optional yet in case it was defined it shouldn't be empty ? HOT 2
- Performance
- Publish to deno.land/x HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from runtypes.