本章節說明了程式碼範例中使用的功能,但不是 TypeScript 本身的一部分。
本書中顯示的程式碼範例會透過單元測試自動測試。作業的預期結果會透過下列斷言函式從Node.js 模組assert
檢查
assert.equal()
透過===
測試相等性assert.deepEqual()
透過深入比較巢狀物件(包含陣列)來測試相等性。assert.throws()
如果回呼參數沒有擲回例外狀況,就會抱怨。以下是如何使用這些斷言的範例
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)
第一行中的匯入陳述式使用嚴格斷言模式(使用===
,而不是==
)。它通常會在程式碼範例中省略。
您也會看到靜態類型斷言。
%inferred-type
在一般 TypeScript 中只是一個註解,描述 TypeScript 為下一行推斷的類型
// %inferred-type: number
= 123; let num
@ts-expect-error
會抑制 TypeScript 中的靜態錯誤。在本書中,抑制的錯誤總是會被提及。這在一般 TypeScript 中既不需要,也不會做任何事。
.throws(
assert// @ts-expect-error: Object is possibly 'null'. (2531)
=> null.myProperty,
() ; TypeError)
請注意,我們以前需要eval()
才能不受到 TypeScript 的警告。