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.
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.)
//%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:
.
These tools are related:
- TypeScript TwoSlasher: https://github.com/microsoft/TypeScript-Website/tree/v2/packages/ts-twoslasher
- Example: https://www.typescriptlang.org/v2/en/tsconfig#strictFunctionTypes
- Upsides:
- Powerful
- Awesome for web content (tooltips, colors, etc.)
- Downsides:
- Doesn’t tie errors to specific lines in the code
- Less suited for PDFs and print
- dtslint: https://github.com/microsoft/dtslint
- Upside: standard
- Downside:
- No way to check for specific errors
- Slightly more work to set up (AFAICT)
- tsd: https://github.com/SamVerschueren/tsd
- Downside:
- No way to check for specific errors
- Unsure if its custom TypeScript version changes how other code behaves
- Downside:
So far, this approach covers all of my needs for the following TypeScript blog posts:
- https://2ality.com/2020/01/typescript-enums.html
- https://2ality.com/2020/01/special-values-typescript.html
- https://2ality.com/2020/01/typing-objects-typescript.html
Is anything missing?