-
-
Notifications
You must be signed in to change notification settings - Fork 281
feat: add guard action for narrowing using type predicates #1204
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
Open
EskiMojo14
wants to merge
4
commits into
fabian-hiller:main
Choose a base branch
from
EskiMojo14:guard
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+744
−0
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import { describe, expectTypeOf, test } from 'vitest'; | ||
| import { pipe } from '../../methods/index.ts'; | ||
| import { number, string } from '../../schemas/index.ts'; | ||
| import type { InferInput, InferIssue, InferOutput } from '../../types/index.ts'; | ||
| import type { GuardAction, GuardIssue } from './guard.ts'; | ||
| import { guard } from './guard.ts'; | ||
|
|
||
| describe('guard', () => { | ||
| type PixelString = `${number}px`; | ||
| const isPixelString = (input: string): input is PixelString => | ||
| /^\d+px$/u.test(input); | ||
|
|
||
| describe('should return action object', () => { | ||
| test('with no message', () => { | ||
| expectTypeOf(guard(isPixelString)).toEqualTypeOf< | ||
| GuardAction<string, PixelString, undefined> | ||
| >(); | ||
| }); | ||
| test('with string message', () => { | ||
| expectTypeOf( | ||
| guard<string, PixelString, 'message'>(isPixelString, 'message') | ||
| ).toEqualTypeOf<GuardAction<string, PixelString, 'message'>>(); | ||
| }); | ||
|
|
||
| test('with function message', () => { | ||
| expectTypeOf( | ||
| guard<string, PixelString, () => string>(isPixelString, () => 'message') | ||
| ).toEqualTypeOf<GuardAction<string, PixelString, () => string>>(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('should infer correct types', () => { | ||
| test('of input', () => { | ||
| expectTypeOf< | ||
| InferInput<GuardAction<string, PixelString, undefined>> | ||
| >().toEqualTypeOf<string>(); | ||
| }); | ||
|
|
||
| test('of output', () => { | ||
| expectTypeOf< | ||
| InferOutput<GuardAction<string, PixelString, undefined>> | ||
| >().toEqualTypeOf<PixelString>(); | ||
| }); | ||
|
|
||
| test('of issue', () => { | ||
| expectTypeOf< | ||
| InferIssue<GuardAction<string, PixelString, undefined>> | ||
| >().toEqualTypeOf<GuardIssue<string, PixelString>>(); | ||
| }); | ||
| }); | ||
|
|
||
| test('should infer correct type in pipe', () => { | ||
| pipe( | ||
| string(), | ||
| guard((input) => { | ||
| expectTypeOf(input).toEqualTypeOf<string>(); | ||
| return isPixelString(input); | ||
| }) | ||
| ); | ||
| }); | ||
|
|
||
| test("should error if pipe input doesn't match", () => { | ||
| pipe( | ||
| number(), | ||
| // @ts-expect-error | ||
| guard(isPixelString) | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { describe, expect, test } from 'vitest'; | ||
| import type { FailureDataset } from '../../types/dataset.ts'; | ||
| import type { GuardAction, GuardIssue } from './guard.ts'; | ||
| import { guard } from './guard.ts'; | ||
|
|
||
| describe('guard', () => { | ||
| type PixelString = `${number}px`; | ||
| const isPixelString = (input: string): input is PixelString => | ||
| /^\d+px$/u.test(input); | ||
|
|
||
| const baseAction: Omit< | ||
| GuardAction<string, PixelString, undefined>, | ||
| 'message' | ||
| > = { | ||
| kind: 'transformation', | ||
| type: 'guard', | ||
| reference: guard, | ||
| requirement: isPixelString, | ||
| async: false, | ||
| '~run': expect.any(Function), | ||
| }; | ||
|
|
||
| describe('should return action object', () => { | ||
| test('with undefined message', () => { | ||
| const action: GuardAction<string, PixelString, undefined> = { | ||
| ...baseAction, | ||
| message: undefined, | ||
| }; | ||
| expect(guard(isPixelString)).toStrictEqual(action); | ||
| expect(guard(isPixelString, undefined)).toStrictEqual(action); | ||
| }); | ||
|
|
||
| test('with string message', () => { | ||
| const action: GuardAction<string, PixelString, 'message'> = { | ||
| ...baseAction, | ||
| message: 'message', | ||
| }; | ||
| expect(guard(isPixelString, 'message')).toStrictEqual(action); | ||
| }); | ||
|
|
||
| test('with function message', () => { | ||
| const message = () => 'message'; | ||
| const action: GuardAction<string, PixelString, typeof message> = { | ||
| ...baseAction, | ||
| message, | ||
| }; | ||
| expect(guard(isPixelString, message)).toStrictEqual(action); | ||
| }); | ||
| }); | ||
|
|
||
| test('should return dataset without issues', () => { | ||
| const action = guard(isPixelString); | ||
| const outputDataset = { typed: true, value: '123px' }; | ||
| expect(action['~run']({ typed: true, value: '123px' }, {})).toStrictEqual( | ||
| outputDataset | ||
| ); | ||
| }); | ||
|
|
||
| test('should return dataset with issues', () => { | ||
| const action = guard(isPixelString, 'message'); | ||
| const baseIssue: Omit< | ||
| GuardIssue<string, PixelString>, | ||
| 'input' | 'received' | ||
| > = { | ||
| kind: 'transformation', | ||
| type: 'guard', | ||
| expected: null, | ||
| message: 'message', | ||
| requirement: isPixelString, | ||
| path: undefined, | ||
| issues: undefined, | ||
| lang: undefined, | ||
| abortEarly: undefined, | ||
| abortPipeEarly: undefined, | ||
| }; | ||
|
|
||
| expect(action['~run']({ typed: true, value: '123' }, {})).toStrictEqual({ | ||
| typed: false, | ||
| value: '123', | ||
| issues: [ | ||
| { | ||
| ...baseIssue, | ||
| input: '123', | ||
| received: '"123"', | ||
| }, | ||
| ], | ||
| } satisfies FailureDataset<GuardIssue<string, PixelString>>); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import type { | ||
| BaseIssue, | ||
| BaseTransformation, | ||
| ErrorMessage, | ||
| } from '../../types/index.ts'; | ||
| import { _addIssue } from '../../utils/index.ts'; | ||
|
|
||
| export type Guard<TInput, TOutput extends TInput> = ( | ||
| input: TInput | ||
| ) => input is TOutput; | ||
|
|
||
| /** | ||
| * Guard issue interface. | ||
| */ | ||
| export interface GuardIssue<TInput, TOutput extends TInput> | ||
| extends BaseIssue<TInput> { | ||
| /** | ||
| * The issue kind. | ||
| */ | ||
| readonly kind: 'transformation'; | ||
| /** | ||
| * The validation type. | ||
| */ | ||
| readonly type: 'guard'; | ||
| /** | ||
| * The validation requirement. | ||
| */ | ||
| readonly requirement: Guard<TInput, TOutput>; | ||
| } | ||
|
|
||
| /** | ||
| * Guard action interface. | ||
| */ | ||
| export interface GuardAction< | ||
| TInput, | ||
| TOutput extends TInput, | ||
| TMessage extends ErrorMessage<GuardIssue<TInput, TOutput>> | undefined, | ||
| > extends BaseTransformation<TInput, TOutput, GuardIssue<TInput, TOutput>> { | ||
| /** | ||
| * The action type. | ||
| */ | ||
| readonly type: 'guard'; | ||
| /** | ||
| * The action reference. | ||
| */ | ||
| readonly reference: typeof guard; | ||
| /** | ||
| * The guard function. | ||
| */ | ||
| readonly requirement: Guard<TInput, TOutput>; | ||
| /** | ||
| * The error message. | ||
| */ | ||
| readonly message: TMessage; | ||
| } | ||
| /** | ||
| * Creates a guard validation action. | ||
| * | ||
| * @param requirement The guard function. | ||
| * | ||
| * @returns A guard action. | ||
| */ | ||
| export function guard<TInput, TOutput extends TInput>( | ||
| requirement: Guard<TInput, TOutput> | ||
| ): GuardAction<TInput, TOutput, undefined>; | ||
|
|
||
| /** | ||
| * Creates a guard validation action. | ||
| * | ||
| * @param requirement The guard function. | ||
| * @param message The error message. | ||
| * | ||
| * @returns A guard action. | ||
| */ | ||
| export function guard< | ||
| TInput, | ||
| TOutput extends TInput, | ||
| const TMessage extends ErrorMessage<GuardIssue<TInput, TOutput>> | undefined, | ||
| >( | ||
| requirement: Guard<TInput, TOutput>, | ||
| message: TMessage | ||
| ): GuardAction<TInput, TOutput, TMessage>; | ||
|
|
||
| // @__NO_SIDE_EFFECTS__ | ||
| export function guard( | ||
| requirement: Guard<unknown, unknown>, | ||
| message?: ErrorMessage<GuardIssue<unknown, unknown>> | ||
| ): GuardAction< | ||
| unknown, | ||
| unknown, | ||
| ErrorMessage<GuardIssue<unknown, unknown>> | undefined | ||
| > { | ||
| return { | ||
| kind: 'transformation', | ||
| type: 'guard', | ||
| reference: guard, | ||
| async: false, | ||
| requirement, | ||
| message, | ||
| '~run'(dataset, config) { | ||
| if (dataset.typed && !this.requirement(dataset.value)) { | ||
| _addIssue(this, 'input', dataset, config); | ||
| // @ts-expect-error | ||
| dataset.typed = false; | ||
| } | ||
| return dataset; | ||
| }, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from './guard.ts'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| --- | ||
| title: guard | ||
| description: Creates a guard transformation action. | ||
| source: /actions/guard/guard.ts | ||
| contributors: | ||
| - EskiMojo14 | ||
| --- | ||
|
|
||
| import { ApiList, Property } from '~/components'; | ||
| import { properties } from './properties'; | ||
|
|
||
| # guard | ||
|
|
||
| Creates a guard transformation action. | ||
|
|
||
| ```ts | ||
| const Action = v.guard<TInput, TOutput, TMessage>(requirement, message); | ||
| ``` | ||
|
|
||
| ## Generics | ||
|
|
||
| - `TInput` <Property {...properties.TInput} /> | ||
| - `TOutput` <Property {...properties.TOutput} /> | ||
| - `TMessage` <Property {...properties.TMessage} /> | ||
|
|
||
| ## Parameters | ||
|
|
||
| - `requirement` <Property {...properties.requirement} /> | ||
| - `message` <Property {...properties.message} /> | ||
|
|
||
| ### Explanation | ||
|
|
||
| With `guard` you can freely validate the input and return `true` if it is valid or `false` otherwise. If the input does not match your `requirement`, you can use `message` to customize the error message. | ||
|
|
||
| This is especially useful if you have an existing type predicate (for example, from an external library). | ||
|
|
||
| > `guard` is useful for narrowing known types. For validating completely unknown values, consider [`custom`](../custom/) instead. | ||
|
|
||
| ## Returns | ||
|
|
||
| - `Action` <Property {...properties.Action} /> | ||
|
|
||
| ## Examples | ||
|
|
||
| The following examples show how `guard` can be used. | ||
|
|
||
| ### Pixel string schema | ||
|
|
||
| Schema to validate a pixel string. | ||
|
|
||
| ```ts | ||
| const PixelStringSchema = v.pipe( | ||
| v.string(), | ||
| v.guard((input): input is `${number}px` => /^\d+px$/.test(input)) | ||
| ); | ||
| ``` | ||
|
|
||
| ### Axios Error schema | ||
|
|
||
| Schema to validate an object containing an Axios error. | ||
|
|
||
| ```ts | ||
| import { isAxiosError } from 'axios'; | ||
|
|
||
| const AxiosErrorSchema = v.object({ | ||
| error: v.pipe( | ||
| v.instance(Error), | ||
| v.guard(isAxiosError, 'The error is not an Axios error.') | ||
| ), | ||
| }); | ||
| ``` | ||
|
|
||
| ## Related | ||
|
|
||
| The following APIs can be combined with `guard`. | ||
|
|
||
| ### Schemas | ||
|
|
||
| <ApiList items={['any', 'custom', 'instance', 'object', 'unknown']} /> | ||
|
|
||
| ### Methods | ||
|
|
||
| <ApiList items={['pipe']} /> | ||
|
|
||
| ### Utils | ||
|
|
||
| <ApiList items={['isOfKind', 'isOfType']} /> | ||
|
|
||
| ### Actions | ||
|
|
||
| <ApiList items={['check', 'rawCheck']} /> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.