diff --git a/README.md b/README.md index 4702db6..f307b00 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Additionally, `is*Of` (or `is.*Of`) functions return type predicate functions to predicate types of `x` more precisely like: ```typescript -import { is } from "./mod.ts"; +import { is, PredicateType } from "./mod.ts"; const isArticle = is.ObjectOf({ title: is.String, @@ -48,6 +48,8 @@ const isArticle = is.ObjectOf({ ])), }); +type Article = PredicateType; + const a: unknown = { title: "Awesome article", body: "This is an awesome article", diff --git a/is.ts b/is.ts index 1ee9fb0..de06d53 100644 --- a/is.ts +++ b/is.ts @@ -3,6 +3,11 @@ */ export type Predicate = (x: unknown) => x is T; +/** + * A type predicated by Predicate + */ +export type PredicateType

= P extends Predicate ? T : never; + /** * Return `true` if the type of `x` is `string`. */ diff --git a/is_test.ts b/is_test.ts index e5ecfc4..ca6af53 100644 --- a/is_test.ts +++ b/is_test.ts @@ -1,11 +1,11 @@ import { assertEquals, assertStrictEquals, -} from "https://deno.land/std@0.200.0/testing/asserts.ts"; +} from "https://deno.land/std@0.202.0/assert/mod.ts"; import type { AssertTrue, IsExact, -} from "https://deno.land/std@0.200.0/testing/types.ts"; +} from "https://deno.land/std@0.202.0/testing/types.ts"; import is, { isAllOf, isArray, @@ -31,6 +31,7 @@ import is, { isUndefined, isUniformTupleOf, Predicate, + PredicateType, } from "./is.ts"; const examples = { @@ -83,6 +84,30 @@ async function testWithExamples( } } +Deno.test("PredicateType", () => { + const isArticle = is.ObjectOf({ + title: is.String, + body: is.String, + refs: is.ArrayOf(is.OneOf([ + is.String, + is.ObjectOf({ + name: is.String, + url: is.String, + }), + ])), + }); + type _ = AssertTrue< + IsExact< + PredicateType, + { + title: string; + body: string; + refs: (string | { name: string; url: string })[]; + } + > + >; +}); + Deno.test("isString", async (t) => { await testWithExamples(t, isString, { validExamples: ["string"] }); }); diff --git a/util_test.ts b/util_test.ts index 38abd00..51cdae3 100644 --- a/util_test.ts +++ b/util_test.ts @@ -1,7 +1,7 @@ import { assertStrictEquals, assertThrows, -} from "https://deno.land/std@0.200.0/testing/asserts.ts"; +} from "https://deno.land/std@0.202.0/assert/mod.ts"; import { assert, AssertError,