https://github.com/buschtoens/combine-type-predicates
Combine user-defined type guards / type predicates as unions and intersections.
https://github.com/buschtoens/combine-type-predicates
intersection-types type-guard type-guards type-predicates typescript union-types
Last synced: 10 months ago
JSON representation
Combine user-defined type guards / type predicates as unions and intersections.
- Host: GitHub
- URL: https://github.com/buschtoens/combine-type-predicates
- Owner: buschtoens
- License: isc
- Created: 2020-04-01T17:06:26.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2023-12-15T14:48:37.000Z (about 2 years ago)
- Last Synced: 2024-10-09T12:42:36.974Z (over 1 year ago)
- Topics: intersection-types, type-guard, type-guards, type-predicates, typescript, union-types
- Language: TypeScript
- Size: 83 KB
- Stars: 7
- Watchers: 3
- Forks: 1
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# combine-type-predicates
[](https://github.com/buschtoens/combine-type-predicates/actions)
[](http://badge.fury.io/js/combine-type-predicates)
[](http://badge.fury.io/js/combine-type-predicates)
[](https://github.com/prettier/prettier)
[](https://dependabot.com/)
[](https://david-dm.org/buschtoens/combine-type-predicates)
[](https://david-dm.org/buschtoens/combine-type-predicates?type=dev)
Combine [user-defined type guards / type predicates][user-defined-type-guards]
as [unions][union] and [intersections][intersection].
[user-defined-type-guards]: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
[union]: https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types
[intersection]: https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types
```ts
import { isSome, isEvery } from 'combine-type-predicates';
type Foo = { foo: boolean; baz: number };
type Bar = { bar: symbol; baz: string };
const isFoo = (v: unknown): v is Foo
=> typeof v.foo === 'boolean' && typeof v.baz === 'number';
const isBar = (v: unknown): v is Bar
=> typeof v.bar === 'symbol' && typeof v.baz === 'string';
const isFooOrBar = isSome(isFoo, isBar);
// => (subject: unknown) => subject is Foo | Bar
const isFooAndBar = isEvery(isFoo, isBar);
// => (subject: unknown) => subject is Foo & Bar
const x: unknown = undefined;
if (isFooOrBar(x)) {
x.baz; // => string | number
if ('foo' in x) {
x.foo; // => boolean
} else {
x.bar; // => symbol
}
}
if (isFooAndBar(x)) {
x.foo; // => boolean
x.bar; // => symbol
x.baz; // => never (no such thing as `string & number`)
}
```