Skip to content

Commit

Permalink
feat: checked cast with TypedMatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
turadg committed Sep 27, 2023
1 parent 31ed402 commit 2e79cfd
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/internal/src/typeCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { mustMatch } from '@endo/patterns';

/**
* @template {import('./types.js').TypedMatcher} M
* @param {unknown} specimen
* @param {M} shape
* @returns {import('./types.js').MatcherType<M>}
*/
export const cast = (specimen, shape) => {
mustMatch(specimen, shape);
return specimen;
};
10 changes: 10 additions & 0 deletions packages/internal/src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* eslint-disable max-classes-per-file */
import type { Matcher } from '@endo/patterns';

export declare class Callback<I extends (...args: unknown[]) => any> {
private iface: I;

Expand All @@ -18,3 +20,11 @@ export declare class SyncCallback<

public isSync: true;
}

declare const type: unique symbol;
export declare type TypedMatcher<T = unknown> = Matcher & {
readonly [type]: T;
};
export declare type MatcherType<M> = M extends TypedMatcher<infer T>
? T
: never;
19 changes: 19 additions & 0 deletions packages/internal/test/test-typeCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// @ts-check
import test from 'ava';

import { M } from '@endo/patterns';
import { cast } from '../src/typeCheck.js';

const Mstring = /** @type {import('../src/types.js').TypedMatcher<string>} */ (
M.string()
);

const unnknownString = /** @type {unknown} */ ('');

test('cast', t => {

Check failure on line 13 in packages/internal/test/test-typeCheck.js

View workflow job for this annotation

GitHub Actions / lint-rest

't' is defined but never used. Allowed unused args must match /^_/u
// @ts-expect-error unknown type
unnknownString.length;
// @ts-expect-error not any
cast(unnknownString, Mstring).missing;
cast(unnknownString, Mstring).length;
});

0 comments on commit 2e79cfd

Please sign in to comment.