function requireNoNilElements<T>(values: T[], message?: string): NonNullable<T>[];
function requireNoNilElements<T>(values: readonly T[], message?: string): readonly NonNullable<T>[];
function requireNoNilElements<T>(values: Set<T>, message?: string): Set<NonNullable<T>>;
function requireNoNilElements<K, V>(values: Map<K, V>, message?: string): Map<K, NonNullable<V>>;
function requireNoNilElements<T extends null | undefined>(values: T, message?: string): T;
function requireNoNilElements(values: unknown, message?: string): unknown;
Колекція з діркою проходить будь-яку іншу перевірку: вона не null, не порожня і є коректним масивом. Пропуск зринає значно пізніше — порожньою коміркою або Cannot read properties of undefined. Ця функція ловить його на межі й повертає колекцію з типом без null і undefined.
Приймається масив, Set або Map — у Map перевіряються значення, а не ключі. Колекція null чи undefined проходить наскрізь: цей випадок належить requireNonNull, і дві перевірки поспіль не мають повідомляти про нього двічі. Порожня колекція проходить. Перевіряється лише верхній рівень, вкладений масив непрозорий. Дірки в масиві вважаються undefined, тож [1, , 3] відхиляється.
Параметри
Параметр
Тип
Опис
values
unknown
Колекція, що перевіряється.
message(необов'язковий)
string
Повідомлення винятку. Якщо не задано, використовується типове.
Повертає
unknown — той самий об'єкт колекції з типом елементів без null і undefined.
Винятки
Виняток
Умова
IllegalArgumentException
елемент дорівнює null або undefined.
IllegalArgumentException
values не є масивом, Set чи Map.
Приклади
Перевірка рядка перед записом
/**
* Appends a contact row, refusing a row with a gap in it rather than writing a
* blank cell that shows up as a bug days later.
*/
export function appendContact(
sheet: GoogleAppsScript.Spreadsheet.Sheet,
name: string | null,
email: string | null
): void {
const row = requireNoNilElements([name, email], "name and email are both required");
sheet.getRange(sheet.getLastRow() + 1, 1, 1, row.length).setValues([row]);
}
function appendContact(sheet, name, email) {
const row = requireNoNilElements([name, email], "name and email are both required");
sheet.getRange(sheet.getLastRow() + 1, 1, 1, row.length).setValues([row]);
}
Звуження типу елементів
import { requireNoNilElements } from "apps-script-utils";
const values: Array<string | null> = readColumn();
const names: string[] = requireNoNilElements(values, "the column has empty cells");
Що проходить, а що ні
requireNoNilElements([1, 2, 3]); // => [1, 2, 3] — the same array
requireNoNilElements(new Map([["a", 1]])); // => the same Map
requireNoNilElements([]); // => []
requireNoNilElements(null); // => null — not this guard's concern
requireNoNilElements([1, undefined, 3]); // throws IllegalArgumentException
requireNoNilElements([1, , 3]); // throws — a hole is undefined
Дивіться також
compact — видаляє порожні значення замість відмови.