ยท new features
What is Type Coercion in TypeScript?
Type coercion is when one type of data is automatically changed into another type. For example, TypeScript can change a number into a string. This happens automatically to prevent errors when different types interact.
Type coercion means that one type of data is automatically turned into another type, like when TypeScript changes a number into a string. This process is based on JavaScript's underlying mechanics and takes place automatically to ensure that interactions between different types don't cause errors.
Contents
Example
If you combine a number and a string, JavaScript handles the type changes behind the scenes to ensure a string concatenation:
When the data type is manually changed (by using a method like parseInt
), it's called type conversion. While type coercion and type conversion are similar, there is a clear difference. Type coercion happens implicitly, while type conversion is primarily an explicit action: