Skip to content

Commit

Permalink
👍 Add PredicateType<P> to infer T of Predicate<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
lambdalisue committed Sep 23, 2023
1 parent 815a2fa commit b5a8abf
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -48,6 +48,8 @@ const isArticle = is.ObjectOf({
])),
});

type Article = PredicateType<typeof isArticle>;

const a: unknown = {
title: "Awesome article",
body: "This is an awesome article",
Expand Down
5 changes: 5 additions & 0 deletions is.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
*/
export type Predicate<T> = (x: unknown) => x is T;

/**
* A type predicated by Predicate<T>
*/
export type PredicateType<P> = P extends Predicate<infer T> ? T : never;

/**
* Return `true` if the type of `x` is `string`.
*/
Expand Down
25 changes: 25 additions & 0 deletions is_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import is, {
isUndefined,
isUniformTupleOf,
Predicate,
PredicateType,
} from "./is.ts";

const examples = {
Expand Down Expand Up @@ -83,6 +84,30 @@ async function testWithExamples<T>(
}
}

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<typeof isArticle>,
{
title: string;
body: string;
refs: (string | { name: string; url: string })[];
}
>
>;
});

Deno.test("isString", async (t) => {
await testWithExamples(t, isString, { validExamples: ["string"] });
});
Expand Down

0 comments on commit b5a8abf

Please sign in to comment.