TypeScript Version: 2.6.1
Code
Symbols cannot be implicitly coerced to strings, unlike other types. They can only be coerced explicitly. The last two lines of code throw runtime errors like TypeError: Cannot convert a Symbol value to a string:
var symbol = Symbol('foo');
console.log(symbol);
console.log(String(symbol));
console.log("" + 6);
console.log("" + /foo/);
console.log(`${symbol}`); // Runtime Error
console.log("" + symbol); // Runtime Error
When down emitting, the string literal is emitted as the last line, so the run-time behaviour is consistent between ES6 and down emitted code, but in both cases, TypeScript could identify them at errors at design time and prevent implicit coercion.
Expected behavior:
That TypeScript would error on the last two lines, replicating the run-time error, thereby statically identifying the error.
Actual behavior:
No errors.
I had no idea that some of these were errors. The second to last line being an error freaks me out... I definitely would value the compiler's help here.
@aluanhaddad yeah, we had been using string literals for explicit implicit coercion (if that is a thing) and were about to do it for a symbol, but double checked at run-time and realised that it didn't work!
The same behavior would be expected for BigInt as well, so there's that to consider.
looks like an error indeed. we should flag this while checking
To be specific, nothing else changes, only symbols for now; we will handle other builtin types like BigInt as they come.
PRs are welcomed.
Most helpful comment
The same behavior would be expected for BigInt as well, so there's that to consider.