Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use TypeScript assert condition signature for invariant(condition, message) #12

Merged
merged 1 commit into from
Oct 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 0 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,6 @@ Equivalent to calling `console.warn(...args)`.

The `Error` subclass thrown by failed `invariant` calls.

This class is especially useful when writing TypeScript, because
```ts
invariant(typeof value === "number", "not a number");
console.log(value * 2); // type error!
```
doesn't tell TypeScript anything useful about `value`, whereas the following code can take full advantage of TypeScript's [conditional type narrowing](https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html) functionality:
```ts
if (typeof value !== "number") {
throw InvariantError("not a number");
}
// TypeScript understands that value must be a number here:
console.log(value * 2);
```

### Build-time usage (`rollup-plugin-invariant`)

If you're using [Rollup](https://rollupjs.org) to bundle your code, or using a library that was bundled using Rollup and `rollup-plugin-invariant`, then the above utilities will be transformed so that minifiers can strip the long error strings from your production bundle.
Expand Down
9 changes: 8 additions & 1 deletion packages/rollup-plugin-invariant/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import * as recast from "recast";
const b = recast.types.builders;
const { createFilter } = require("rollup-pluginutils");

export default function invariantPlugin(options = {} as any) {
export interface PluginOptions {
errorCodes?: boolean;
importProcessPolyfill?: boolean;
include?: Array<string | RegExp> | string | RegExp | null,
exclude?: Array<string | RegExp> | string | RegExp | null,
}

export default function invariantPlugin(options: PluginOptions = {}) {
const filter = createFilter(options.include, options.exclude);
let nextErrorCode = 1;

Expand Down
6 changes: 2 additions & 4 deletions packages/rollup-plugin-invariant/src/tests.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from "assert";
import fs from "fs";
import plugin from "./plugin";
import plugin, { PluginOptions } from './plugin';
import * as recast from "recast";
import { parse } from "recast/parsers/acorn";
import invariant, { InvariantError } from "ts-invariant";
Expand All @@ -15,9 +15,7 @@ describe("rollup-plugin-invariant", function () {

function check(
id: string,
options?: {
errorCodes: boolean;
},
options?: PluginOptions,
) {
const path = require.resolve(id);
const code = fs.readFileSync(path, "utf8");
Expand Down
5 changes: 4 additions & 1 deletion packages/ts-invariant/src/invariant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ export class InvariantError extends Error {
}
}

export function invariant(condition: any, message?: string | number) {
export function invariant(
condition: any,
message?: string | number,
): asserts condition {
if (!condition) {
throw new InvariantError(message);
}
Expand Down
8 changes: 8 additions & 0 deletions packages/ts-invariant/src/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,12 @@ describe("ts-invariant", function () {
assert.strictEqual(typeof process.versions.node, "string");
}
});

it("should let TypeScript know about the assertion made", function () {
const value: { foo?: { bar?: string } } = {foo: {bar: "bar"}};
invariant(value.foo, 'fail');

// On compile time this should not raise "TS2532: Object is possibly 'undefined'."
assert.strictEqual(value.foo.bar, "bar");
});
});
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"types": ["node", "mocha"],
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"esModuleInterop": true
}
}