Table of contents

  1. 1. Example

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.


If you combine a number and a string, JavaScript handles the type changes behind the scenes to ensure a string concatenation:

const number: number = 42;
const message: string = 'The answer is: ' + number; // `number` is coerced to a string

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:

const text: string = '10';
console.log(parseInt(text)); // `text` is converted to a string