gajus / gajus/flow-runtime

Support arbitrary conversions with a Type#convert method

Open
#241 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
797
Forks
49
PR merge metrics
No merged PRs in 30d

Description

This is a:

- [ ] Bug Report
- [x] Feature Request
- [ ] Question
- [ ] Other

Which concerns:

- [x] flow-runtime
- [ ] babel-plugin-flow-runtime
- [ ] flow-runtime-validators
- [ ] flow-runtime-mobx
- [ ] flow-config-parser
- [ ] The documentation website

---

No affordance for `convert` behavior:

```js
type Request = {
// Feature: convert strings to numbers.
quantity: number,
// Feature: convert datetime strings (v.dateTime) or numeric timestamps to Dates.
sessionTime: Date,
};

const RequestType = (reify: Type);

// One possibility for a conversion decoration API. flow-runtime ingests the explicit
// type on the input parameter to determine how to widen the type.
RequestType.getProperty('quantity').addConversion((raw: string) => {
const value = parseInt(raw, 10);
if (isNaN(value)) {
throw new TypeError('expected a base-10 integer');
}
return value;
});

// The convert method is a modified assert that expands the supported types to include
// types that can be casted.
const value = RequestType.convert({
// value.quantity could become 12, or this behavior could be customized like in
// the constraint model by mutating a PermissiveNumber type.
quantity: '12.0',
// value.sessionTime becomes Date(2019-11-19T01:53:00.000Z)
sessionTime: '2019-11-19T01:53:00Z',
});
```

A v1 here might be to just decorate all `Type`s with `convert` methods and `conversion` arrays that we can extend with `addConversion`. This would mostly be trying to solve the same use-cases as [joi's `convert` option](https://hapi.dev/family/joi/?v=16.1.7#anyvalidatevalue-options).

A v2 might be to support a conversion where the types in and the types out are entirely disjoint - e.g. `convert(input: string | number): Date` but via a declarative syntax

A v3 might be to include default conversion functionality like `string` -> `number`, but that'd require a bit more exploration.

I'm open to working on this; just curious if y'all have thoughts on the API/concerns about the implementation.

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by reviewing the flow-runtime Type API and its existing assert behavior, then compare the proposed v1, v2, and v3 conversion scopes with joi's convert option. Done means agreeing on a conversion API and behavior for the quantity and sessionTime examples, with coverage for the supported conversion cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.