- The unknown type is a safer alternative to any. It represents a value whose type is not known at the time of assignment, but you must perform type checks before you can perform operations on it. This enforces type safety while still allowing for flexible types.
- When to use it: Use unknown when you don’t know the type of a value upfront, but want to enforce type checking before working with it. It’s useful when receiving data from dynamic sources (like user input or external APIs). It ensures that you perform proper type checks before operating on values of type `unknown`, promoting safer coding practices.
- The `unknown` type acts as a top type in the TypeScript type system, which means it can hold any value. However, you cannot perform operations directly on values of type `unknown` without first narrowing down their type or providing explicit type assertions.
function getValue(): unknown {
// Simulating a dynamic value
return Math.random() > 0.5 ? "Hello" : 42;
}
const result = getValue();
// Type checking with `unknown`
if (typeof result === "string") {
console.log(result.toUpperCase());
} else if (typeof result === "number") {
console.log(result.toFixed(2));
} else {
console.log("Unknown type");
}
- In the above example, the `getValue` function returns an `unknown` value. It randomly returns either a string or a number. When we assign the result to the `result` variable, its type is inferred as `unknown`.
- To perform operations on `result`, we need to narrow down its type. In the subsequent `if` and `else if` statements, we use the `typeof` operator to check the type of `result` and perform specific operations accordingly. If the type is a string, we can safely call the `toUpperCase()` method, and if it's a number, we can call the `toFixed()` method. Otherwise, we handle the case of an unknown type.
- By using `unknown` in this example, we ensure that we explicitly check the type before performing any operations. This approach eliminates runtime errors that could occur if we assumed the wrong type.
- Another common technique when dealing with `unknown` types is to use type assertions or type guards to narrow down the type within a particular code block. This helps TypeScript's type inference system to understand the specific type and enable related operations. Here's an example:
function processData(data: unknown) {
if (typeof data === "object" && data !== null) {
// Type assertion for object type
const person = data as { name: string; age: number };
console.log(`Name: ${person.name}, Age: ${person.age}`);
} else {
console.log("Invalid data");
}
}
processData({ name: "John", age: 30 });
- In this example, the `processData` function receives an `unknown` value named `data`. We use a type guard to check if `data` is an object and not `null`. Then, we assert its type as `{ name: string; age: number }` using the `as` keyword, which informs TypeScript that we know the structure of the object.
- By narrowing down the type, we can safely access the `name` and `age` properties without TypeScript raising type errors.
- To summarize, the `unknown` type in TypeScript is a way to handle values with unknown types in a type-safe manner. It enforces explicit type checks and promotes safer coding practices by preventing operations on values without proper type narrowing or type assertions.
No comments:
Post a Comment