Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active February 17, 2020 21:21
Show Gist options
  • Save rauschma/f6d93edbad3e1a7789dce61548034a54 to your computer and use it in GitHub Desktop.
Save rauschma/f6d93edbad3e1a7789dce61548034a54 to your computer and use it in GitHub Desktop.

Testing TypeScript examples

Challenges:

  • Testing expected static errors. In JavaScript, expected dynamic errors can be tested via:
    • assert.throws(() => eval('const myVar;'), SyntaxError);
    • assert.throws(() => null.someProp, TypeError);
  • Testing expected inferred types.

Approach:

  • Pass 1—runtime errors: Run the examples as unit tests; for example, via ts-node and Mocha or AVA.
  • Pass 2—static errors: Use a static checker for the unit test code.
    • I’m working on such a checker and will hopefully have time to open-source it.

Static checker: expected static errors

Approach: Ingore the errors via @ts-ignore

function func1(x: Object) { }
func1('abc'); // OK

function func2(x: object) { }
//@ts-ignore: Argument of type '"abc"' is not assignable to parameter of type 'object'. (2345)
func2('abc');

The static checker warns if the static error doesn’t match text and number after @ts-ignore:.

(This functionality would be useful for TypeScript code in general.)

Static checker: expected inferred types

//%inferred-type: Object
const obj1 = new Object();

//%inferred-type: object
const obj2 = Reflect.getPrototypeOf({});

//%inferred-type: {}
const obj3 = {};

//%inferred-type: () => number
function myFunc() {
  return 123;
}

The static checker warns if the inferred type doesn’t match what’s mentioned after %inferred-type:.

Related tools

These tools are related:

Anything missing?

So far, this approach covers all of my needs for the following TypeScript blog posts:

Is anything missing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment