🔷 TypeScript Q13 / 101

What is unknown type?

AI-Powered Answer ✓ Answered

The `unknown` type in TypeScript is a type-safe alternative to `any`. It signifies that a variable can hold a value of any type, but unlike `any`, you cannot perform any operations on an `unknown` value until its type has been explicitly narrowed.

What is `unknown`?

unknown is a top type, meaning any value can be assigned to it. It's essentially the type-safe version of any. When a variable is typed as unknown, TypeScript forces you to perform type checking (type narrowing) before you can interact with that variable in any specific way.

The core principle of unknown is 'safety first'. You cannot call methods, access properties, or use operators (like +, -, *, /) on a value of type unknown directly. This strictness helps prevent runtime errors by ensuring that you, the developer, explicitly handle all possible types.

Why use `unknown`?

  • Type Safety: It encourages robust code by requiring explicit type checks, reducing the likelihood of unexpected runtime errors.
  • Explicit Type Narrowing: Forces developers to think about and handle all potential types a variable might hold, leading to more thorough error handling.
  • Handling External Data: Ideal for scenarios where the type of incoming data (e.g., from an API, user input, or parsing JSON) is not immediately certain but needs to be validated before use.
  • Safer any replacement: When you don't know the type, unknown is almost always a better choice than any because it enforces checking.

How to work with `unknown`

To safely interact with an unknown value, you must first narrow its type using type guards. Common type guards include typeof, instanceof, or custom user-defined type guards.

typescript
function processValue(value: unknown) {
  if (typeof value === 'string') {
    console.log(`It's a string: ${value.toUpperCase()}`);
  } else if (typeof value === 'number') {
    console.log(`It's a number: ${value * 2}`);
  } else if (value instanceof Array) {
    console.log(`It's an array with ${value.length} elements.`);
  } else {
    console.log('Type not recognized or handled.');
  }
}

processValue("hello");    // It's a string: HELLO
processValue(123);        // It's a number: 246
processValue([1, 2, 3]);  // It's an array with 3 elements.
processValue(true);       // Type not recognized or handled.

unknown vs. any

Feature`unknown``any`
Type SafetyStrict: Requires type narrowing before use. Prevents operations until type is known.Loose: Bypasses type checking. Allows any operation without prior validation, potentially leading to runtime errors.
AssignmentCan be assigned any type. Can only be assigned to `unknown` or `any`.Can be assigned any type. Can be assigned to any type.
UsageBest for data whose type is not known but needs to be validated.Use with extreme caution, often for quick hacks or legacy code integration where types are impossible to infer.
Compiler ChecksForces explicit type checks.Disables type checks.