Type errors in TypeScript occur when a variable is assigned a value of a type that does not match its expected type. These errors can lead to unexpected behavior in your applications, and addressing them is crucial for maintaining code quality. Below are some common mistakes and how to handle them.
Mistake:
let age: number;
age = "30"; // Error: Type 'string' is not assignable to type 'number'.
Solution:
Ensure the assigned value matches the declared type.
let age: number;
age = 30; // Correct: Assigning a number.
Mistake:
function greet(name: string) {
return `Hello, ${name}!`;
}
greet(123); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Solution:
Pass a value that matches the expected type.
function greet(name: string) {
return `Hello, ${name}!`;
}
greet("Alice"); // Correct: Passing a string.
Mistake:
let numbers: number[];
numbers = [1, 2, "three"]; // Error: Type 'string' is not assignable to type 'number'.
Solution:
Ensure all elements in the array are of the declared type.
let numbers: number[];
numbers = [1, 2, 3]; // Correct: All elements are numbers.
Mistake:
let data: any;
data = "Hello";
console.log(data.length); // Works but defeats the purpose of TypeScript's type safety.
Solution:
Use specific types instead of ‘any’ to maintain type safety.
let data: string;
data = "Hello";
console.log(data.length); // Correct: 'data' is now of type 'string'.
Mistake:
function add(a: number, b: number): number {
return a + b;
}
const result: string = add(5, 10); // Error: Type 'number' is not assignable to type 'string'.
Solution:
Ensure the return type matches the expected type.
function add(a: number, b: number): number {
return a + b;
}
const result: number = add(5, 10); // Correct: 'result' is now of type 'number'.
Type errors in TypeScript can be easily identified and resolved by ensuring that your variable assignments, function parameters, and return types align with their declared types. By paying close attention to these common mistakes, you can leverage TypeScript’s strengths to create robust, error-free code.