unknown type
- TypeScript course
- Beginner
- Lesson 26/89
- 4 min
Learn safe type checking with unknown.
The unknown type
The unknown type, like any, accepts any value but requires you to check its type before using it. This provides flexibility while keeping type safety. You cannot access an unknown value without a type check.
let x: unknown = "merhaba";
if (typeof x === "string") {
console.log(x.toUpperCase()); // "MERHABA"
}unknown is used as a safe alternative to any.
Type guard
To use an unknown value, you narrow its type with a type guard. The most common type guard is the typeof operator. After narrowing, you can safely perform type-specific operations.
let deger: unknown = 42;
if (typeof deger === "number") {
console.log(deger * 2); // 84
}A type guard converts unknown to a specific type and enables safe access.
Practice Type guard with unknown
Declare a variable named girdi of type unknown with value "merhaba". Use typeof to check whether it is a string; if so, convert it to uppercase with toUpperCase and print it with console.log.
Starter code
// girdi adında bir unknown değişkeni tanımla
// değeri "merhaba" olsun
// typeof ile string kontrolü yap
// string ise büyük harfe çevirip yazdırSample solution
let girdi: unknown = "merhaba";
if (typeof girdi === "string") {
console.log(girdi.toUpperCase());
}Expected output
MERHABA
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the key difference between <code>unknown</code> and <code>any</code>?
- unknown is faster than any
- unknown allows no value assignments
- unknown requires type checking before use Correct answer
- There is no difference between unknown and any
Explanation: <code>unknown</code> accepts any value but requires a type check (type guard) before use; <code>any</code> has no such check and is therefore unsafe.
2 Add the type guard
let deger: unknown = "merhaba";
if (typeof deger === ____) { console.log(deger.toUpperCase()); }
let deger: unknown = "merhaba";
if (typeof deger === "string") { console.log(deger.toUpperCase()); }
Explanation: Since the variable's value is a string, the <code>typeof</code> check must be against <code>"string"</code> to use the <code>toUpperCase</code> method.
3 unknown concepts
| Term | Meaning |
|---|---|
unknown |
Type check required before use |
typeof x === "string" |
Type guard |
unknown vs any |
unknown is safer |
Tür koruyucu |
Type narrowing operation |