TypeScript Error Explained: Type 'string' is not assignable to type 'number'

Learn why TypeScript shows the error 'Type string is not assignable to type number', what it means, and how to fix it with simple explanations and examples.

When working with TypeScript, you might encounter an error that says "Type 'string' is not assignable to type 'number'". This is a common mistake for beginners who are learning how TypeScript enforces types. This article will help you understand why this error occurs, what it means in simple terms, and how to resolve it so you can write error-free TypeScript code.

The error "Type 'string' is not assignable to type 'number'" happens because TypeScript expects a certain data type (in this case, a number), but instead, it is receiving a string value. TypeScript uses static typing, which means it checks the types of your variables, function parameters, and return values at compile time. If a value doesn’t match the expected type, TypeScript throws an error to help catch potential mistakes early. This kind of type checking is very helpful when working with variables, type annotations, and function parameters.

typescript
let age: number;
age = "25"; // Error: Type 'string' is not assignable to type 'number'

function doubleNumber(num: number): number {
  return num * 2;
}

doubleNumber("10"); // Error here as well

To fix this error, you need to ensure that the values you assign to variables or pass to functions match the declared type. In the example above, the variable "age" should be assigned a number, not a string. If you have a string representation of a number, you can convert it using functions such as Number() or parseInt(). Also, make sure function arguments respect their parameter types. This way, TypeScript won’t complain and your code will be safer and easier to maintain.

A common mistake when encountering this error is mixing data types accidentally, for example, reading user input from an HTML form which is always a string, then trying to assign or use it as a number without conversion. Another pitfall is not using type assertions or type narrowing correctly. Using union types or type guards are related concepts that help manage variables that might hold multiple types, but trying to assign a string directly to a pure number type always causes this error.

In summary, the "Type 'string' is not assignable to type 'number'" error is TypeScript’s way of making sure your code respects type safety. By understanding how types work, managing type annotations properly, and converting values when necessary, you can avoid this error and write cleaner, bug-resistant TypeScript code. Always double-check your declared types and the actual data types to prevent such issues.