When performing data assignment in TypeScript, assigning data that are not type compatible will cause the error “Type ‘#’ is not assignable to type ‘##'”. In this article, we will show how to avoid this error by using union type and using type assertions.
What causes the error “Type ‘#’ is not assignable to type ‘##'” in TypeScript
// We declare a variable whose data type is number let price = 199; // An error occurred when assigning string type to number type price = "299";
Type 'string' is not assignable to type 'number'.
In the above example, we declare a variable
price. Then we assign the number 199 to it and Typescript will automatically put the variable price into the type number. After that, we assign the string type to this variable and an error occurs because in the beginning, TypeScript specified the variable price is a type of number.
The solution to solve this problem
The solution to solve this problem is we can use a union data type for the price variable so that this variable can store both string and number data types, or we can use a common method are type assertions to tell TypeScript about the type of data we want to work with.
Using union type
Using the union type, you can declare a variable that can contain many different data types, so when performing the assignment of the specified data types, the program will not cause an error.
// Use union data type for variable price let price: number | string = 199; price = "299"; console.log(price);
Using type assertions
Using type assertions, we can tell TypeScript that the data type assigned is the type we declared at the beginning, thus avoiding errors.
let price = 199; // Using type assertions to convert to number type price = "299" as unknown as number; console.log(price);
In the above example, we will convert to an unknown type and then convert to the number type.
To conclude, we already know the cause of “Type ‘#’ is not assignable to type ‘##'” error in TypeScript is due to data type incompatibility. We fixed it by using union type and converting data by type assertions. To avoid errors, we should specify the data types to which the variable will be assigned first by using union type.
Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).