CodeBlanks Logo Icon CodeBlanks

never type

Learn unreachable code with never.

The never type

The never type represents values that can never occur. A function that always throws an error or runs an infinite loop has the return type never. This type marks unreachable code.

function patla(mesaj: string): never {
  throw new Error(mesaj);
}

never indicates that the function does not end normally.

never and unreachable code

never also marks unreachable code paths. If a function ends with throw, the code after throw never runs. This code is of type never and is flagged by the compiler.

function patla(): never {
  throw new Error("durdur");
  console.log("buraya hiç gelinmez");  // never
}

never helps catch logic errors in the program's flow.

Practice never function and error catching

Define a function named patla with a mesaj parameter of type string and return type never. The function should throw new Error(mesaj). Use try-catch to call patla("sistem hatası") and print the caught error's message with console.log.

Starter code

index.ts
// patla adında bir fonksiyon tanımla
// mesaj parametresi string, dönüş türü never olsun
// fonksiyon new Error(mesaj) fırlatsın
// try-catch ile çağır ve hatanın mesajını yazdır

Sample solution

index.ts
function patla(mesaj: string): never {
    throw new Error(mesaj);
}
try {
    patla("sistem hatası");
} catch (e) {
    console.log("yakalandi: " + e.message);
}

Expected output

yakalandi: sistem hatası

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which function has the <code>never</code> return type?

  • function patla(msg: string): never { throw new Error(msg); } Correct answer
  • function selam(): void { console.log("hi"); }
  • function al(): string { return "x"; }
  • function topla(a: number, b: number): number { return a + b; }

Explanation: The <code>patla</code> function, which always throws, does not end normally; its return type is <code>never</code>. The others either return a value or end normally.

2 Add the never return type

Question
function patla(mesaj: string): ____ { throw new Error(mesaj); }
Answer
function patla(mesaj: string): never { throw new Error(mesaj); }

Explanation: Since the function always throws an error, it does not return normally; the correct return type is <code>never</code>.

3 never concepts

Term Meaning
never Value that never occurs
throw new Error() Function does not end normally
never dönüş türü Function does not return
Sonsuz döngü Fits the never type

All lessons in Beginner