Tackling TypeScript
請支持本書:購買捐款
(廣告,請不要阻擋。)

6 本書中使用的符號



本章節說明了程式碼範例中使用的功能,但不是 TypeScript 本身的一部分。

6.1 測試斷言(動態)

本書中顯示的程式碼範例會透過單元測試自動測試。作業的預期結果會透過下列斷言函式從Node.js 模組assert檢查

以下是如何使用這些斷言的範例

import {strict as assert} from 'assert';

assert.equal(3 + ' apples', '3 apples');

assert.deepEqual(
  [...['a', 'b'], ...['c', 'd']],
  ['a', 'b', 'c', 'd']);

assert.throws(
  () => eval('null.myProperty'),
  TypeError);

第一行中的匯入陳述式使用嚴格斷言模式(使用===,而不是==)。它通常會在程式碼範例中省略。

6.2 類型斷言(靜態)

您也會看到靜態類型斷言。

%inferred-type在一般 TypeScript 中只是一個註解,描述 TypeScript 為下一行推斷的類型

// %inferred-type: number
let num = 123;

@ts-expect-error會抑制 TypeScript 中的靜態錯誤。在本書中,抑制的錯誤總是會被提及。這在一般 TypeScript 中既不需要,也不會做任何事。

assert.throws(
  // @ts-expect-error: Object is possibly 'null'. (2531)
  () => null.myProperty,
  TypeError);

請注意,我們以前需要eval()才能不受到 TypeScript 的警告。