Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/dsherret/conditional-type-checks

Types for testing TypeScript types.
https://github.com/dsherret/conditional-type-checks

Last synced: 19 days ago
JSON representation

Types for testing TypeScript types.

Awesome Lists containing this project

README

        

# Conditional Type Checks

[![npm version](https://badge.fury.io/js/conditional-type-checks.svg)](https://badge.fury.io/js/conditional-type-checks)
[![CI](https://github.com/dsherret/conditional-type-checks/workflows/CI/badge.svg)](https://github.com/dsherret/conditional-type-checks/actions?query=workflow%3ACI)
[![deno doc](https://doc.deno.land/badge.svg)](https://doc.deno.land/https/deno.land/x/conditional_type_checks/mod.ts)
[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges)

As TypeScript's type system becomes more complex, it's useful to be able to write tests for what a type should be.

This library offers reusable conditional types to help test your types.

## Type Checks

These will resolve to the type `true` when they match and `false` otherwise.

- `IsNullable` - Checks if `T` is possibly `null` or `undefined`.
- `IsExact` - Checks if `T` exactly matches `U`.
- `Has` - Checks if `T` has `U`.
- `NotHas` - Checks if `T` does not have `U`.
- `IsAny` - Checks if `T` is the `any` type.
- `IsNever` - Checks if `T` is the `never` type.
- `IsUnknown` - Checks if `T` is the `unknown` type.
- More to come...

## Ways to Test

Use what you prefer:

1. The `AssertTrue`, `AssertFalse`, or `Assert` types.
2. The `assert` function.

### Use with `AssertTrue`, `AssertFalse`, and `Assert`

Doing a test:

```ts
import type {
AssertFalse,
AssertTrue,
Has,
IsNever,
IsNullable,
} from "https://deno.land/x/conditional_type_checks/mod.ts";

const result = someFunction(someArg);

type _test =
| AssertTrue | IsNullable>
| AssertFalse>
| Assert, true>;
```

**Warning:** Do not use an intersection type between checks (ex. `Has & IsNever`) because it will cause everything to pass if only one of the checks passes.

### Use with `assert`

Doing a test:

```ts
import {
assert,
IsExact,
} from "https://deno.land/x/conditional_type_checks/mod.ts";

const result = someFunction(someArg);

// compile error if the type of `result` is not exactly `string | number`
assert>(true);
```

Failure:

```ts
// causes a compile error that `true` is not assignable to `false`
assert>(true); // string is not nullable
```

## npm Install

```
npm install --save-dev conditional-type-checks
```