DEV Community

Shashank Trivedi
Shashank Trivedi

Posted on

Typescript unknown type

unknown ? ?

The unknown type in TypeScript is useful when you're dealing with a value that could be of any type but want to enforce type checking to ensure type safety before performing any operations

function processInput(input: unknown) {
  if (typeof input === "string") {
    console.log(`String input: ${input.toUpperCase()}`);
  } else if (typeof input === "number") {
    console.log(`Number input doubled: ${input * 2}`);
  } else {
    console.log('Unknown type of input');
  }
}

processInput("TypeScript"); // String input: TYPESCRIPT
processInput(21);           // Number input doubled: 42
processInput(true);         // Unknown type of input
Enter fullscreen mode Exit fullscreen mode

Unknown with instanceof

class Car {
  drive() {
    console.log("Driving a car!");
  }
}

class Bike {
  pedal() {
    console.log("Pedaling a bike!");
  }
}

function useVehicle(vehicle: unknown) {
  if (vehicle instanceof Car) {
    vehicle.drive(); // Safe to call 'drive' method
  } else if (vehicle instanceof Bike) {
    vehicle.pedal(); // Safe to call 'pedal' method
  } else {
    console.log("Unknown vehicle");
  }
}

useVehicle(new Car());  // Driving a car!
useVehicle(new Bike()); // Pedaling a bike!
useVehicle({});         // Unknown vehicle
Enter fullscreen mode Exit fullscreen mode

Unknown or any

  1. The unknown type in TypeScript is generally considered safer and more strict than the any type. While both unknown and any type can be used to represent values of any type, the key difference lies in how they enforce type safety.

  2. You must perform a type check before performing operations on values of type unknown. Where as you can perform any operation on an any type value without type checking. This leads to potential runtime errors because TypeScript won't alert you to type issues.

  3. unknown: Forces you to think about type safety. If you attempt to use an unknown value without narrowing it first, TypeScript will show an error, ensuring you're handling the value correctly. any Allows you to bypass type checks, meaning you can call methods that may not exist on a value. This could lead to runtime errors that are difficult to track down.

unknown or Generics

Use Generics when:

  • You want flexibility but expect the same type throughout the function, class, or structure.

  • You want TypeScript to enforce that the input and output types match or relate in a certain way.

  • You’re working with reusable components (like functions, classes, or interfaces) that should adapt to multiple types without losing type safety.

  • For example, if you’re creating a utility function like identity(value: T): T, generics ensure that whatever type you pass in is the same type returned, making it type-safe and flexible.

Use unknown when:

  • You're dealing with dynamic or untrusted data where the exact type is completely uncertain at the time of writing, and you need to enforce checks at runtime.

  • You don't want to assume the type and need explicit runtime checks before doing any operations on the data.

  • You're working with data from external sources such as APIs, user input, or libraries, where type information isn't known upfront.

Top comments (0)