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.
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.
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.
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.
Let's explore how the "unknown" type can be beneficial in different scenarios.
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.
Ask anything...