Skip to content

Commit b5a8abf

Browse files
committed
👍 Add PredicateType<P> to infer T of Predicate<T>
1 parent 815a2fa commit b5a8abf

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Additionally, `is*Of` (or `is.*Of`) functions return type predicate functions to
3434
predicate types of `x` more precisely like:
3535

3636
```typescript
37-
import { is } from "./mod.ts";
37+
import { is, PredicateType } from "./mod.ts";
3838

3939
const isArticle = is.ObjectOf({
4040
title: is.String,
@@ -48,6 +48,8 @@ const isArticle = is.ObjectOf({
4848
])),
4949
});
5050

51+
type Article = PredicateType<typeof isArticle>;
52+
5153
const a: unknown = {
5254
title: "Awesome article",
5355
body: "This is an awesome article",

is.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
*/
44
export type Predicate<T> = (x: unknown) => x is T;
55

6+
/**
7+
* A type predicated by Predicate<T>
8+
*/
9+
export type PredicateType<P> = P extends Predicate<infer T> ? T : never;
10+
611
/**
712
* Return `true` if the type of `x` is `string`.
813
*/

is_test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import is, {
3131
isUndefined,
3232
isUniformTupleOf,
3333
Predicate,
34+
PredicateType,
3435
} from "./is.ts";
3536

3637
const examples = {
@@ -83,6 +84,30 @@ async function testWithExamples<T>(
8384
}
8485
}
8586

87+
Deno.test("PredicateType", () => {
88+
const isArticle = is.ObjectOf({
89+
title: is.String,
90+
body: is.String,
91+
refs: is.ArrayOf(is.OneOf([
92+
is.String,
93+
is.ObjectOf({
94+
name: is.String,
95+
url: is.String,
96+
}),
97+
])),
98+
});
99+
type _ = AssertTrue<
100+
IsExact<
101+
PredicateType<typeof isArticle>,
102+
{
103+
title: string;
104+
body: string;
105+
refs: (string | { name: string; url: string })[];
106+
}
107+
>
108+
>;
109+
});
110+
86111
Deno.test("isString", async (t) => {
87112
await testWithExamples(t, isString, { validExamples: ["string"] });
88113
});

0 commit comments

Comments
 (0)