Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
In TypeScript, as in most programming languages, errors can be categorized into several types based on their nature and the situations in which they occur. Here are some common types of errors you may encounter in TypeScript:
Parser Errors: These occur when the code violates the language's syntax rules, such as missing or misplaced parentheses, curly braces, or semicolons.
1. Type Mismatch Errors: These happen when you attempt to assign a value of one type to a variable of a different type.
javascriptlet age: number = "30";
// Type 'string' is not assignable to type 'number'.
In this example, the variable age is declared as a number, but an attempt is made to assign a string to it, causing a type error.
2. Type Inference Errors: TypeScript can't determine a variable's type because it's either ambiguous or has no initial value.
javascriptlet x;
x = "Hello";
x = 42;
TypeScript can't infer the type of x because it's declared without an explicit type. While this provides flexibility, it can lead to errors if you later assign values of different types to it.
3. Type Assertion Errors: Occur when you assert a type that is not compatible with the variable's actual type.
javascriptlet message: any = "Hello, TypeScript!";
let length: number = message.length;
// Object is possibly 'null'
In this example, message is of type any, and an attempt is made to access the length property of it without proper type assertion.
4. Non-Existent Property Errors: Trying to access a property or method that doesn't exist on an object or variable.
javascriptlet person: { name: string } = { age: 30 };
// Property 'name' does not exist on type '{ age: number; }'.
The type of person is declared to have a name property, but the object assigned to it does not have that property.
5. Implicit Any Errors:
javascriptlet value;
value = "Hello";
let length: number = value.length;
// Object is of type 'unknown'.
When TypeScript is configured to use the strict mode, implicit any types are not allowed, and this can lead to type errors. Here, value is treated as unknown until its type is explicitly defined.
1. Null and Undefined Errors: Occur when trying to access properties or methods on null or undefined values.
javascript// Type Checking Against null or undefined:
let name: string = "Alice";
name = null; // Error: Type 'null' is not assignable to type 'string'.
// Type Inference with null or undefined:
let age;
age = null;
let newAge: number = age; // Error: Type 'null' is not assignable to type 'number'.
// Handling Possibly Undefined or Null Variables:
let user: { name?: string } = {};
let userNameLength = user.name.length; // Error: Object is possibly 'undefined'.
// Checking for Null or Undefined Values:
let data: string | null = fetchData();
if (data !== null) {
console.log(data.length); // No error
}
// Using Optional Chaining:
let user = {
profile: {
email: "user@example.com"
}
};
let userEmail = user.profile?.email; // No error, userEmail might be undefined.
2. Object Modification Errors: Happen when you try to add or modify properties on objects with fixed shapes (e.g., objects with frozen or sealed properties).
javascriptinterface Person {
name: string;
age: number;
}
const person: Person = { name: "Alice", age: 30 };
person.address = "123 Main St"; // Error: Property 'address' does not exist on type 'Person'.
// Attempting to modify a frozen object will result in a runtime error
const user = Object.freeze({ name: "Bob", age: 25 });
user.age = 26; // Runtime Error in JavaScript (TypeScript won't catch this).
// Attempting to modify a frozen object will result in a runtime error
const product = Object.seal({ name: "Widget", price: 10.0 });
product.price = 12.0; // Allowed
product.description = "A useful widget"; // Error: Cannot add property 'description', object is not extensible.
// The properties of the original interface cannot be modified or removed
interface Animal {
name: string;
}
interface Bird extends Animal {
// Error: Property 'name' cannot be declared in an object type literal.
name: string;
wingspan: number;
}
3. Function Errors: Occur when you invoke a function with the wrong number or type of arguments.
javascriptfunction greet(name: string): void {
console.log(`Hello, ${name}`);
}
greet(42);
// Argument of type '42' is not assignable to parameter of type 'string'.
You can create custom errors by extending the Error class or by defining your own error classes. These are used to provide specific error messages and information in your code.
When working with APIs, file systems, or network requests, you can encounter errors related to network issues, file not found, or permissions.
Promises and async/await code can generate errors related to rejected promises or unhandled exceptions within asynchronous operations.
These errors are caused by incorrect mathematical calculations or logical flaws in the code.
Errors related to security vulnerabilities, such as cross-site scripting (XSS) or SQL injection, may also occur in TypeScript.
Errors generated by third-party libraries and dependencies used in your project.
Errors related to environmental issues, such as incorrect configurations, missing dependencies, or outdated tools.
Errors and warnings generated by code linters and style checkers, such as ESLint
and TSLint
, which help enforce coding standards and catch issues like code style violations and potential bugs.
Errors related to the infrastructure and deployment environment, such as server crashes, database connection failures, and cloud service outages.
Handling errors effectively in your TypeScript code, regardless of their type, is essential to ensure that your applications are robust and reliable. Depending on the type of error, you may employ different error-handling strategies, including try...catch blocks, validation, error logging, and reporting.