Skip to content

Identify implicit symbol to string coercion errors #19666

Closed

Description

@kitsonk

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.

Activity

  1. aluanhaddad commented on Nov 2, 2017

    @aluanhaddad
    Contributor

    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.

  2. kitsonk commented on Nov 3, 2017

    @kitsonk
    ContributorAuthor

    Aluan Haddad (@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!

  3. DanielRosenwasser commented on Nov 3, 2017

    @DanielRosenwasser
    Member

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

  4. mhegazy commented on Nov 6, 2017

    @mhegazy
    Contributor

    looks like an error indeed. we should flag this while checking

  5. mhegazy commented on Nov 6, 2017

    @mhegazy
    Contributor

    To be specific, nothing else changes, only symbols for now; we will handle other builtin types like BigInt as they come.

  6. mhegazy commented on Nov 6, 2017

    @mhegazy
    Contributor

    PRs are welcomed.

  7. added this to the milestone on Jan 4, 2018
  8. modified the milestones: , TypeScript 2.9 on Mar 30, 2018
  9. added a commit that references this issue on Mar 30, 2018
    31c3ef5
  10. locked and limited conversation to collaborators on Jul 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CommittedThe team has roadmapped this issueFixedA PR has been merged for this issueHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions