Obie opisują kształt danych i są często wymienne, ale mają różne możliwości.
interface User { name: string; age: number; }
type User2 = { name: string; age: number; };
Obie opisują kształt danych i są często wymienne, ale mają różne możliwości.
interface User { name: string; age: number; }
type User2 = { name: string; age: number; };
type to ogólne alias dla dowolnego typu — primitywów, unii, tuple'i, mapped types. interface opisuje tylko kształty object/function.
interface nie potrafi zrobićtype ID = string | number; // unions
type Pair = [number, number]; // tuples
type Name = User["name"]; // indexed/mapped/conditional types
type Nullable<T> = T | null; // wrap any type
Interfaces obsługują declaration merging (wiele deklaracji się łączy) i są idiomatycznym sposobem na rozszerzanie/augmentowanie, w tym augmentowanie typów bibliotek trzecich.
interface Box { width: number; }
interface Box { height: number; } // declaration merging — both merge into one
// Box now has width AND height
Zwyczajna konwencja: używaj interface dla kształtów object i publicznych API (lepsze komunikaty błędów, rozszerzalne, scalane) i type gdy potrzebujesz unii, tuple'i lub innych operacji typów. Wybierz jedno jako domyślne dla spójności — wiele zespołów domyślnie używa interface dla obiektów i sięga po type tylko gdy potrzebna jest jego dodatkowa moc.
interface Admin extends User { role: string; } // interface
type Admin2 = User & { role: string }; // type uses intersection
Biblioteka pytań rekrutacyjnych IT ze szczegółowymi odpowiedziami — od Juniora do Seniora.
Wesprzyj