Summary - Special types
- TypeScript course
- Beginner
- Lesson 29/89
- 4 min
Write a program comparing any, unknown, never, and void types.
Summary - Special types
Special types serve different purposes: any disables type checking, unknown allows use after a type check, never marks unreachable code, and void indicates functions that return no value. Choosing the right type improves code safety and readability.
function logla(m: string): void { console.log(m); }
let veri: unknown = "test";
if (typeof veri === "string") { logla(veri); }Special types provide TypeScript's balance of flexibility and safety.
Practice void and unknown together
Define a function named goster with a mesaj parameter of type string and return type void. The function should print mesaj with console.log. Declare a variable named veri of type unknown with value "test". Use typeof to check if it is a string; if so, call goster with veri.
Starter code
// goster adında bir void fonksiyon tanımla
// mesaj parametresini console.log ile yazdır
// veri adında bir unknown değişken tanımla, değeri "test"
// typeof ile string kontrolü yap
// string ise goster'i veri ile çağırSample solution
function goster(mesaj: string): void {
console.log(mesaj);
}
let veri: unknown = "test";
if (typeof veri === "string") {
goster(veri);
}Expected output
test
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which return type is suitable for a function that always throws an error?
- unknown
- void
- any
- never Correct answer
Explanation: A function that always throws an error does not end normally; therefore the correct return type is <code>never</code>. <code>void</code> is for functions that end normally.
2 Choose the correct type
function isle(deger: ____) { if (typeof deger === "string") { console.log(deger); } }
function isle(deger: unknown) { if (typeof deger === "string") { console.log(deger); } }
Explanation: Since the parameter is checked with <code>typeof</code> before use, the safe choice is <code>unknown</code>; <code>any</code> would make the check unnecessary, and <code>void</code> and <code>never</code> are not suitable as parameter types.
3 Special types summary
| Term | Meaning |
|---|---|
any |
Disables type safety |
unknown |
Requires check for safe use |
never |
Function never returns |
void |
Performs action, no value |