Skip to content

Commit

Permalink
Add TypeEqual generic type
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey committed Mar 25, 2019
1 parent a236eb2 commit 39f04b5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
5 changes: 4 additions & 1 deletion README.md
Expand Up @@ -18,9 +18,12 @@ npm install ts-expect --save
## Usage

```ts
import { expectType, TypeOf } from "ts-expect";
import { expectType, TypeOf, TypeEqual } from "ts-expect";

expectType<string>(123); // Compiler error!

expectType<TypeOf<number, 123>>(true);
expectType<TypeEqual<"test", "test">>(true);
```

### Examples
Expand Down
26 changes: 24 additions & 2 deletions src/index.spec.ts
@@ -1,4 +1,4 @@
import { expectType, TypeOf } from "./index";
import { expectType, TypeOf, TypeEqual } from "./index";

describe("ts expect", () => {
it("should expect types", () => {
Expand All @@ -10,7 +10,29 @@ describe("ts expect", () => {
const result = expectType("");

expect(result).toEqual(undefined);
});

describe("TypeOf", () => {
it("should support type of checks", () => {
expectType<TypeOf<number, 123>>(true);
expectType<TypeOf<123, number>>(false);
expectType<TypeOf<string, "test">>(true);
expectType<TypeOf<"test", string>>(false);
});
});

describe("TypeEqual", () => {
it("should check types are equal", () => {
expectType<TypeEqual<123, 123>>(true);
expectType<TypeEqual<123, number>>(false);
expectType<TypeEqual<number, 123>>(false);
expectType<TypeEqual<number, number>>(true);

expectType<TypeEqual<false, true>>(false);
expectType<TypeEqual<false, boolean>>(false);

expectType<TypeOf<typeof result, void>>(true);
expectType<TypeEqual<1 | 2, 1>>(false);
expectType<TypeEqual<1 | 2, 1 | 2>>(true);
});
});
});
5 changes: 5 additions & 0 deletions src/index.ts
Expand Up @@ -3,6 +3,11 @@
*/
export type TypeOf<T, U> = Exclude<U, T> extends never ? true : false;

/**
* Checks that `T` is equal to `U`.
*/
export type TypeEqual<T, U> = Exclude<T, U> extends never ? Exclude<U, T> extends never ? true : false : false;

/**
* Assert the parameter is of a specific type.
*/
Expand Down

0 comments on commit 39f04b5

Please sign in to comment.