TypeScript: Jak sprawdzić, czy obiekt implementuje dany interfejs?

Opublikowano: - tagi:

Czy obiekt implementuje interfejs?

TypeScript pozwala na sprawdzenie, czy obiekt implementuje konkretny interfejs za pomocą strażnika typu (ang.: typ-safe guard). Taki strażnik musi zostać napisany przez programistę.

Przykład:

Interfejs:

interface IPerson {
    name: string
    age: number
    weight: number
}

I funkcja, która sprawdzi, czy podana wartość implementuje interfejs:

function isPerson(person: unknown): person is IPerson {
    return typeof person === 'object' && person !== null && 'name' in person && 'age' in person && 'weight' in person;
}

Przykład wywołania:

console.log('null: ', isPerson(null)) // false
console.log('undefined: ', isPerson(undefined)) // false
console.log('[]: ', isPerson([])) // false
console.log('{ name: "Kowalski" }: ', isPerson({ name: "Kowalski" })) // false
console.log('{ name: "Kowalski", age: 25, weight: 75 }: ', isPerson({ name: "Kowalski", age: 25, weight: 75 })) // true

Podsumowanie: Luty 2025

Opublikowano: - tagi:

W lutym opublikowałem 1 wpis:


JavaScript:

  1. Jak pobrać N ostatnich elementów tablicy?

Przeczytałem 1 książkę:

  1. Szum — Blake Crouch

Przesłuchałem 4 audiobooki:

  1. Zły syn — Jarek Skurzyński
  2. Choose Yourself — James Altucher
  3. Medicus — Noah Gordon
  4. Ukochane równanie profesora — Yōko Ogawa

JavaScript: Jak pobrać N ostatnich elementów tablicy?

Opublikowano: - tagi:

Pobieranie ostatnich elementów

Tablica:

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

I potrzebujesz na przykład pobrać 5 ostatnich elementów tablicy. Jak można to zrobić?

Przykład:

const result = items.slice(
  Math.max(items.length - 5, 0)
);

console.log(result); // [6, 7, 8, 9, 10]

Podsumowanie: Styczeń 2025

Opublikowano: - tagi:

W styczniu opublikowałem 1 wpis:


JavaScript:

  1. Vitest: Jak sprawdzić, czy funkcja rzuciła wyjątkiem?

Przeczytałem 2 książki:

  1. Praca z zastanym kodem. Najlepsze techniki — Michael Feathers
  2. Rozdroże kruków — Andrzej Sapkowski

Przesłuchałem 4 audiobooki:

  1. Sekret pacjentki — Loreth Anne White
  2. Mleczarz — Anna Burns
  3. Ja, które nie poznałam mężczyzn — Jacqueline Harpman
  4. Pas Ilmarinena — Marcin Mortka

Vitest: Jak sprawdzić czy funkcja rzuciła wyjątkiem?

Opublikowano: - tagi:

Testowanie wyjątków w Vitest

Mamy prostą funkcję:

function loadFile(fileName?: string): string {
    if (!fileName) {
        throw new Error('File not exist!');
    }

    return 'Some content';
}

I chcemy stestować, czy funkcja rzuca wyjątek. Można to zrobić to w taki sposób:

import { expect, test } from 'vitest';

test('should check file not exist', () => {
    expect(() => loadFile()).toThrowError('File not exist!');
});

Testowanie wersji asynchronicznej

Jak stestować wersją asynchroniczną?

function loadFile(fileName?: string): Promise<string> {
    if (!fileName) {
        throw new Error('File not exist!');
    }

    return Promise.resolve('Some content')
}

Test:

import { expect, test } from 'vitest';

test('should check file not exist', async () => {
    await expect(async () => await loadFile()).rejects.toThrowError('File not exist!');
});