Middle
Cos'è il tipo never in TypeScript e come si differenzia dagli altri tipi?
sobes.tech AI
Risposta dell'AI
Il tipo never in TypeScript viene usato per indicare valori che non si verificano mai. È un tipo per funzioni che non restituiscono mai un valore (ad esempio, che lanciano un errore o si eseguono in modo infinito), o per variabili che non possono avere un valore.
Differenze rispetto ad altri tipi:
- Altri tipi descrivono valori possibili, mentre
neverindica l'assenza di valori. neverè un sottotipo di tutti i tipi, ma nessun tipo è sottotipo dinever(tranneneverstesso).
Esempio:
function error(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while(true) {}
}