Typescript: Identify implicit symbol to string coercion errors

Created on 1 Nov 2017  路  6Comments  路  Source: microsoft/TypeScript

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.

Committed Fixed Suggestion help wanted

Most helpful comment

The same behavior would be expected for BigInt as well, so there's that to consider.

All 6 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bgrieder picture bgrieder  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

siddjain picture siddjain  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments