Basics
TS never Type
Using the never Type
TypeScript never type represents unreachable code used in exhaustive checks.
What is the never Type?
The never
type in TypeScript is a type that represents values that never occur. It is used to indicate unreachable code or to perform exhaustive checks in functions. When a function is expected to never return, it can be annotated with never
. This type is crucial in ensuring that all possible cases are handled in applications, especially when working with discriminated unions.
Use Cases for never Type
The never
type is particularly useful in the following scenarios:
- Exhaustive Checks: Ensuring that all possible cases in a union type are covered.
- Unreachable Code: Indicating that a piece of code will never be executed, such as in a function that throws an error.
Exhaustive Checks with never Type
In TypeScript, you can use the never
type to verify that all possible types in a union have been handled. This is often done in a switch
statement. Let's look at an example:
In the example above, the default
case in the switch
statement is designed never to be reached if all possible cases are handled. If a new shape is added to the Shape
type and not handled in the function, TypeScript will throw a compile-time error.
Indicating Unreachable Code
The never
type can be used to mark code that should never be reached. This is useful in functions that throw exceptions or terminate the program:
In the above example, the throwError
function is annotated with the never
type because it terminates with an exception and never returns a value.
Conclusion
The never
type in TypeScript is a powerful tool for type safety. By using never
, you can ensure that your code handles all possible scenarios, preventing runtime errors and improving code reliability. Understanding and utilizing never
will make your TypeScript code more robust and easier to maintain.