Summary of Why Unknown Types Are Useful

  • michaeluloth.com
  • Article
  • Summarized Content

    Using "unknown" Type in TypeScript

    When working with data from external sources like user input, APIs, or libraries, you can't always be certain of its type. This is where TypeScript's "unknown" type comes in handy. It's a way of explicitly acknowledging that you don't know the actual type of the data.

    • The "unknown" type prevents TypeScript from making assumptions about the data. It's a safety mechanism to ensure that your code doesn't encounter unexpected runtime errors due to incorrect type assumptions.
    • It essentially tells TypeScript, "I don't know the type of this data yet. Let me handle it carefully." This forces you to validate the data before using it, eliminating potential type-related errors.

    Avoiding Unsafe Assumptions

    Let's say you're taking input from a user and expect it to be a string. A naive approach is to assume the input will always be what you expect:

    const getUserInput = (): string => {/*...*/}
     
    const unsafe = () => {
      const data = getUserInput()
      data.toUpperCase()
    }

    This approach may seem harmless, but it creates a potential for runtime errors. If the data is not a string, you'll get a "Cannot read properties of undefined (reading 'toUpperCase')" error.

    Using "unknown" for Safer Data Handling

    To prevent these errors, you can use the "unknown" type in TypeScript.

    // 🤞 Should be a string, but who knows...
    const getUserInput = (): unknown => {/*...*/}
     
    const unsafe = () => {
      const data = getUserInput()
      data.toUpperCase()
      // 🚨 'data' is of type 'unknown'
    }

    By declaring the return type of getUserInput as "unknown", TypeScript now warns you that you're attempting to use string methods on a value whose type is unknown. This forces you to validate the data before attempting to use any string-specific methods.

    Validating Assumptions with Type Checking

    To resolve this warning, you need to validate your assumption about the data's type using type checking:

    const getUserInput = (): unknown => {/*...*/}
     
    const safe = () => {
      const data = getUserInput()
      
      if (typeof data === 'string') {
        data.toUpperCase() // confirmed safe
      } else {
        // handle invalid input
      }
    }

    Here, you explicitly check the type of the data using typeof. This allows you to safely access string methods only when the data is confirmed to be a string, enhancing the safety of your TypeScript code.

    TypeScript "unknown" Type in Action

    Let's explore how the "unknown" type can be beneficial in different scenarios.

    User Input Validation

    • When accepting user input, it's crucial to validate the data type to ensure it conforms to your expectations. The "unknown" type forces you to perform type checks, preventing potential errors caused by unexpected input formats.

    API Response Handling

    • APIs can return data of different types. By using "unknown" for API responses, you can enforce a type-safe approach, validating the data received before processing it.

    Library Integration

    • When integrating third-party libraries, their output might be unpredictable. The "unknown" type safeguards your code by making you explicitly validate the type of data coming from these libraries.

    Benefits of Using the "unknown" Type

    • Enhanced Type Safety: Prevents incorrect assumptions about data types and reduces the risk of runtime errors.
    • Improved Code Maintainability: Promotes explicit type validation, leading to more understandable and predictable code.
    • Robust Error Handling: Allows for better handling of unexpected data types, leading to more resilient applications.

    In Conclusion

    Using the "unknown" type in TypeScript is a powerful technique to write safer, more reliable, and maintainable code. It forces you to think about data validation and type checking, ultimately resulting in more robust applications. By embracing "unknown" and explicit type validation, you can significantly enhance the quality and reliability of your TypeScript programs.

    Discover content by category

    Ask anything...

    Sign Up Free to ask questions about anything you want to learn.