It is a very common error in TypeScript that beginners often face. When this error occurs, your code editor might display the following error message 👇
Why this error occurs ?
The error “Type ‘Number’ is not assignable to type ‘String'” occurs when you try to assign a value of type ‘
Number‘ to a variable or parameter that is expected to be of type ‘
Here’s a simple example that describe the error:
let myString: string = "Hello"; // ⛔️ Type 'Number' not assignable to type 'String' myString = 123;
In the above example, we have a variable called ‘myString’ with the type string. Initially, we assign it the value “Hello”, which is correct. However, if we later try to assign the number 123 to ‘myString’, TypeScript generates an error because the variable can only hold text (strings), not numbers.
In TypeScript, when you see the error message “Type ‘Number’ is not assignable to type ‘String'”, it means you’re trying to put a number into something that specifically requires a string. TypeScript generates this error to prevent the problems that may arise from this mismatch.
How to fix this error ?
To fix the error, you need to use the correct type of value for the variable. If you want to store a word or a sentence (a string) in the “myString” variable, make sure you don’t use a number instead.
But if you want the variable to be able to store both words or sentences (strings) and numbers, you can change the type of the “myString” variable to be able to hold either a string or a number by using the type string | number. This way, the variable can hold different types of values.
let myString: string|number = "Hello"; myString = 123;
In our case we want to store both string and number so we will use type
string | number.