The 'never' Type
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 70 of 73.
The never type represents values that never occur. This might sound confusing at first, but it's actually quite logical when you think about certain scenarios in your code.
The never type is most commonly used for functions that never return normally.
This includes functions that always throw an error or contain infinite loops:
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
// This loop never ends
}
}Unlike void, which indicates a function doesn't return a meaningful value, never indicates that the function never reaches its end point at all. The execution either stops due to an error being thrown or continues indefinitely.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function named throwError that demonstrates the never return type by always throwing an error and never returning normally.
The function should:
- Take a parameter
messageof typestring - Throw a new
Errorwith the provided message - Have an explicit return type of
never
Create a second function named handleOperation that:
- Takes two parameters:
operationof typestringandvalueof typenumber - Returns
value * 2if operation is"double" - Returns
value / 2if operation is"half" - Calls
throwErrorwith the message"Invalid operation: [operation]"for any other operation - Has an explicit return type of
number
Test your functions with the following operations:
- Call
handleOperation("double", 5)and print the result - Call
handleOperation("half", 8)and print the result - Call
handleOperation("triple", 3)and print the result (this will throw an error)
Create additional test cases:
- Call
handleOperation("double", 15)and print the result - Call
handleOperation("half", 20)and print the result
Cheat sheet
The never type represents values that never occur. It's used for functions that never return normally.
Functions that return never include those that always throw errors or contain infinite loops:
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
// This loop never ends
}
}Unlike void (which indicates a function doesn't return a meaningful value), never indicates that the function never reaches its end point at all.
Try it yourself
// TODO: Write your code here
// Create the throwError function with never return type
// Create the handleOperation function with number return type
// Test the functions with try-catch blocks
try {
console.log(handleOperation("double", 5));
} catch (error) {
console.log(`Error: ${(error as Error).message}`);
}
try {
console.log(handleOperation("half", 8));
} catch (error) {
console.log(`Error: ${(error as Error).message}`);
}
try {
console.log(handleOperation("triple", 3));
} catch (error) {
console.log(`Error: ${(error as Error).message}`);
}
try {
console.log(handleOperation("double", 15));
} catch (error) {
console.log(`Error: ${(error as Error).message}`);
}
try {
console.log(handleOperation("half", 20));
} catch (error) {
console.log(`Error: ${(error as Error).message}`);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos8Enums
What is a Numeric Enum?Using Numeric EnumsWhat is a String Enum?Using String EnumsHeterogeneous EnumsRecap: Using Enums11Advanced Topics
Type Assertions Type Guards: in & instanceofThe 'never' TypeNullable Types ('strictNull')Index Signatures for ObjectsRecap: Fine-Tuning Types3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples