
Type Assertion, Type Unknown, and Type Never in TypeScript
Type Assertion, Type Unknown, and Type Never in TypeScript 관련
Type Assertion
Type assertion tells TypeScript to treat a value as a specific type. It does not change the value but helps the compiler understand the type.
let value: unknown = "Hello, TypeScript!";
// Using type assertion to treat 'value' as a string
let strLength: number = (value as string).length;
console.log(strLength); // Output: 18
Here, value
is initially unknown
, but type assertion (as string
) allows treating it as a string.
And here’s an alternative way to write type assertion:
let num = <number>(10);
console.log(num); // Output: 10
The <number>
syntax also performs type assertion.
Type Unknown
Let’s briefly revisit the unknown
type now. Remember that it’s a safer alternative to any
and can hold any value – but TypeScript requires type checking before using it.
let data: unknown;
data = "Hello";
data = 42;
data = true;
// Type checking before using the value
if (typeof data === "string") {
console.log(data.toUpperCase()); // Works only if data is a string
}
Since data
is unknown
, TypeScript does not allow direct operations without checking its type first.
Type Never
The never
type represents values that never occur. It is often used for functions that never return or always throw an error.
function throwError(message: string): never {
throw new Error(message);
}
// throwError("Something went wrong!"); // This function never returns
Here, throwError
does not return anything because it always throws an error.
Example of Type Never in a Switch Case:
type Status = "success" | "failure";
function checkStatus(status: Status): void {
switch (status) {
case "success":
console.log("Operation was successful.");
break;
case "failure":
console.log("Operation failed.");
break;
default:
const unexpected: never = status; // Ensures all cases are handled
}
}
This ensures that all possible values of Status
are handled, preventing unexpected behavior.
Here’s a quick comparison of these different approaches:
Feature | Description |
---|---|
Type Assertion | Tells TypeScript to treat a value as a specific type. |
Unknown Type | Allows storing any value but requires type checking before use. |
Never Type | Represents values that never occur, used for functions that never return. |