Opublikowano:
29.03.2025 - 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 ))
console .log ('undefined: ' , isPerson (undefined ))
console .log ('[]: ' , isPerson ([]))
console .log ('{ name: "Kowalski" }: ' , isPerson ({ name : "Kowalski" }))
console .log ('{ name: "Kowalski", age: 25, weight: 75 }: ' , isPerson ({ name : "Kowalski" , age : 25 , weight : 75 }))
Opublikowano:
28.02.2025 - tagi:
W lutym opublikowałem 1 wpis :
JavaScript :
Jak pobrać N ostatnich elementów tablicy? Przeczytałem 1 książkę:
Szum — Blake CrouchPrzesłuchałem 4 audiobooki:
Zły syn — Jarek SkurzyńskiChoose Yourself — James AltucherMedicus — Noah GordonUkochane równanie profesora — Yōko OgawaOpublikowano:
08.02.2025 - 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);
Opublikowano:
31.01.2025 - tagi:
W styczniu opublikowałem 1 wpis :
JavaScript :
Vitest: Jak sprawdzić, czy funkcja rzuciła wyjątkiem? Przeczytałem 2 książki:
Praca z zastanym kodem. Najlepsze techniki — Michael FeathersRozdroże kruków — Andrzej SapkowskiPrzesłuchałem 4 audiobooki:
Sekret pacjentki — Loreth Anne WhiteMleczarz — Anna BurnsJa, które nie poznałam mężczyzn — Jacqueline HarpmanPas Ilmarinena — Marcin MortkaOpublikowano:
30.01.2025 - 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!' );
});
Nowsze wpisy Poprzednie wpisy