In TypeScript, type coercion is the automatic conversion of values from one data type to another.
Type coercion is generally triggered by context and the use of operators when the language rules don’t receive variables of a specific data type. In the latter case, TypeScript automatically converts values between compatible data types without explicit instructions.
Following are the cases of type coercion:
Consider the code snippet below, which demonstrates the above mentioned type coercion cases in TypeScript:
//Example 1: String to numeric coercionlet numericString: string = "1";let result: number = 5 + +numericString; // Implicit coercion: +"1" converts the string to a numberconsole.log("Example 1: ",result); // Output: 6//Example 2.1: Numeric to string coercionlet stringVar: string = "10"let coercedString: string = 5 + 10 + stringVar;console.log("Example 2.1: ",coercedString)//Example 2.2: Numeric to string coercionlet numericVar: number = 5;let concatenatedString: string = "The value is " + numericVar; // Coerces numberValue to a string for concatenationconsole.log("Example 2.2: ",concatenatedString)//Example 3.1: Truthy and falsy coercionconsole.log("Example 3.1: ",false || numericVar)//Example 3.2: Truthy and falsy coercionconsole.log("Example 3.2: ",true && null)
In this code example:
+numericString
is a key player that converts a string to a number using the unary plus operator.+
operator is acting as a concatenation operator and concatenating the numeric sum 15
with the string type variable.false || numericVar
is evaluated with boolean rules, and since numericVar
is considered truthy, it is returned as the result.true && null
, null
is percieved as a falsy value. The result of this boolean expression is the first falsy value of the expression i.e. null
.Although TypeScript offers type coercion, it still enforces type safety and static type checking. Therefore, some type coercion expressions may lead to compilation errors if the conversion is impossible or violates the language rules. Following is an example of the expressions that will result in errors:
//Type coercion expressions that lead to error//Example 1var num1: number = 10;var num2: string = "5";var result = num1 - num2;console.log(result);//Example 2console.log('true' == true)
Lines 3-5: This is an invalid type coercion leading to an error. Instead of the -
operator, using the +
operator, either as a unary plus operator or a binary plus operator, would have resulted in some kind of a coercion.
Line 9: In this line, the ==
operator will convert both the operands to number
format. Hence the string 'true'
will be converted to NaN
and the boolean true
will be converted to 1
, evaluating the expression to be false
.
Free Resources