Skip to content

Commit

Permalink
[dsch] fix for .restrict and documentation drafted
Browse files Browse the repository at this point in the history
  • Loading branch information
DScheglov committed Mar 24, 2021
1 parent 786ba57 commit deaf22c
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 8 deletions.
5 changes: 5 additions & 0 deletions README.md
Expand Up @@ -30,6 +30,11 @@ type Person = { name: string, age: number };
npm i ts-cast
```

## [Documentation](https://github.com/DScheglov/ts-cast/tree/master/docs)

Read `ts-cast` documentation on github: <br/>
[https://github.com/DScheglov/ts-cast/tree/master/docs](https://github.com/DScheglov/ts-cast/tree/master/docs)

## Getting Started

Let's start with an example:
Expand Down
100 changes: 93 additions & 7 deletions docs/1-engine.md
@@ -1,5 +1,17 @@
# ts-cast &middot; Type Checking Engine API

- [1. CasterFn&lt;T&gt; <sup>`type`</sup>](#1-casterfnt-suptypesup)
- [2. Caster&lt;T&gt; <sup>`type`</sup>](#2-castert-suptypesup)
- [Type Definition](#type-definition)
- [Property `.optional`](#property-optional)
- [Property `.nullable`](#property-nullable)
- [Method `.default`](#method-default)
- [Method `.restrict`](#method-restrict)
- [Method `.map`](#method-map)
- [Method `.validate`](#method-validate)
- [3. casterApi&lt;T&gt; <sup>`fn`</sup>](#3-casterapit-supfnsup)
- [4. createCaster&lt;T&gt; <sup>`fn`</sup>](#4-createcastert-supfnsup)
- [5. validate&lt;T&gt; <sup>`fn`</sup>](#5-validatet-supfnsup)

<a name="1-caster-fn"></a>
## 1. CasterFn&lt;T&gt; <sup>`type`</sup>
Expand Down Expand Up @@ -85,7 +97,9 @@ export interface Caster<T> extends CasterFn<T> {

### Property `.optional`

> `Caster<T | undefined>`
```ts
Caster<T | undefined>
```

The `.optional` property refers to `Caster` of **optional** type. Optional is considered as _could be undefined_.

Expand All @@ -101,7 +115,9 @@ optNumber(null); // throws a TypeError

### Property `.nullable`

> `Caster<T | null>`
```ts
Caster<T | null>
```

The `.nullable` property refers to `Caster` of **nullable** type that means the correspondent caster accepts `null` as valid value.

Expand All @@ -117,7 +133,9 @@ nullableStr(undefined); // throws a TypeError

### Method `.default`

> `(value: T) => Caster<Exclude<T, undefined>>`
```ts
(value: T) => Caster<Exclude<T, undefined>>
```

Creates new `Caster` that replaces `undefined` input with `value` specified as argument.

Expand All @@ -142,7 +160,9 @@ someStr(null); // throws a TypeError

### Method `.restrict`

> `(...rules: RuleFn<Exclude<T, null | undefined>>[]) => Caster<T>`
```ts
(...rules: RuleFn<Exclude<T, null | undefined>>[]) => Caster<T>
```

Creates new `Caster` that cheks if casted value satisfies restrictions described with one ore more `RuleFn`.

Expand All @@ -156,16 +176,20 @@ More details avout restrictions are described in [Narrowing Types](./4-restricti

**Arguments**

| Parameters | Type | Mandatory | Description |
| :--------: | :--------------------------------------: | :-----------------: | :----------------------- |
| Parameters | Type | Mandatory | Description |
| :----------: | :---------------------------------------: | :-----------------: | :----------------------- |
| **...rules** | `RuleFn<Exclude<T, null \| undefined>>[]` | _at least one rule_ | Rules to narrow the type |

**Returns**
- **caster**: `Caster<T>`

### Method `.map`

> `<D>(transform: (value: Exclude<T, null | undefined>) => D) => Caster<D | Exclude<T, Exclude<T, null | undefined>>>;`
```ts
<D>(transform: TransformFn<T. D>) => Caster<D | Exclude<T, Exclude<T, null | undefined>>>;

type TransformFn<T, D> = (value: Exclude<T, null | undefined>) => D;
```

Creates `caster` that addionally transforms casted value to other type keeping `null | undefined` context untouched.

Expand All @@ -189,6 +213,68 @@ ID(123); // returns "123";
export type TID = ReturnType<typeof ID>; // ReturnType<Caster<string>> is string
```

**Arguments**

| Parameter | Type | Mandatory | Description |
| :-----------: | :-----------------: | :-------: | :---------------------------------------------------------------------------------- |
| **transform** | `TransformFn<T, D>` | yes | The function transforms defined non-nullable value of type `T` to value of type `D` |


**Returns**
- **caster**: `Caster<D | Exclude<T, Exclude<T, null | undefined>>>`

### Method `.validate`

```ts
(value: unknown) => ValidationResult<T>;

type ValidationResult<T> = {
ok: boolean;
result?: T;
errors: Array<{ message: string, context: string | undefined }>;
}
```
Validates `value` of `unknown` type and returns a validation result object. The
method doesn't throw TypeErrors if `value` couldn't be casted to type `T` or doesn't
satisfy to restriction rules if available.
**Example**
```ts
import { integer, toBe, gt } from 'ts-cast';

const { validate } = integer.restrict(toBe(gt(0)));

validate(1);
// { ok: true, errors: [], result: 1 }

validate(0);
/**
{
ok: false,
errors: [{ message: 'expected value is greater then 0 but received 0.', context: undefined }]
}
*/

validate('123', 'myValue');
/**
{
ok: false,
errors: [{ message: 'integer is expected in myValue but "123" received.', context: 'myValue' }]
}
*/
```

**Arguments**

| Parameter | Type | Mandatory | Description |
| :-------: | :--: | :-------: | :---------- |
| **value** | `unknown` | yes | The value to be validated |

**Returns**
- **validationResult**: `ValidationResult<T>`

<a name="3-caster-api"></a>
## 3. casterApi&lt;T&gt; <sup>`fn`</sup>

Expand Down
2 changes: 1 addition & 1 deletion src/engine/restrict.ts
Expand Up @@ -20,7 +20,7 @@ export const restrict = <T>(caster: CasterFn<T>, rules: RuleFn<T>[]) => {
): T => {
const typedValue: T = caster(value, context, reportError);

if (!isEmpty(value)) rules.forEach(applyRule(typedValue, context, reportError));
if (!isEmpty(typedValue)) rules.forEach(applyRule(typedValue, context, reportError));

return typedValue;
};
Expand Down

0 comments on commit deaf22c

Please sign in to comment.