Questions
What is the difference between `any` and `unknown` in TypeScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new function that needs to work with a value of an unknown type.
You are not sure whether to use the any type or the unknown type.
The Challenge
Explain the difference between the any and unknown types in TypeScript. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might think that they are interchangeable. They might not be aware of the difference in type safety between the two.
A senior engineer would be able to provide a detailed explanation of the differences between `any` and `unknown`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Feature | any | unknown |
|---|---|---|
| Type Safety | Not type-safe. You can perform any operation on a value of type any. | Type-safe. You must perform a type check before you can perform any operation on a value of type unknown. |
| Use Cases | When you need to opt-out of type checking for a particular value. | When you have a value of an unknown type and you want to be type-safe. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use the unknown type. This is because we have a value of an unknown type, and we want to be type-safe.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
any:
let myVar: any;
myVar.myMethod(); // No error at compile time, but will fail at runtimeunknown:
let myVar: unknown;
// This will raise an error at compile time
// myVar.myMethod();
if (typeof myVar === 'object' && myVar !== null && 'myMethod' in myVar) {
// We can now call myMethod()
} Practice Question
You are working with a value that you know is a string, but you want to be able to call any method on it without getting a type error. Which of the following would you use?