This chapter explains functionality that is used in the code examples, but not part of TypeScript proper.
The code examples shown in this book are tested automatically via unit tests. Expected results of operations are checked via the following assertion functions from the Node.js module assert
:
assert.equal()
tests equality via ===
assert.deepEqual()
tests equality by deeply comparing nested objects (incl. Arrays).assert.throws()
complains if the callback parameter does not throw an exception.This is an example of using these assertions:
import {strict as assert} from 'assert';
.equal(3 + ' apples', '3 apples');
assert
.deepEqual(
assert...['a', 'b'], ...['c', 'd']],
['a', 'b', 'c', 'd']);
[
.throws(
assert=> eval('null.myProperty'),
() ; TypeError)
The import statement in the first line makes use of strict assertion mode (which uses ===
, not ==
). It is usually omitted in code examples.
You’ll also see static type assertions.
%inferred-type
is just a comment in normal TypeScript and describes the type that TypeScript infers for the following line:
// %inferred-type: number
= 123; let num
@ts-expect-error
suppresses static errors in TypeScript. In this book, the suppressed error is always mentioned. That is neither required in plain TypeScript, nor does it do anything there.
.throws(
assert// @ts-expect-error: Object is possibly 'null'. (2531)
=> null.myProperty,
() ; TypeError)
Note that we previously needed eval()
in order to not be warned by TypeScript.