microsoft / microsoft/TypeScript

Improve support for Symbol.toPrimitive

Open
#4,538 6 comments 24 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Proposal Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Presently, TS limits index types to 'string', 'number', 'symbol', or 'any'. That's fine, but consider the following:

class Foo {
    [Symbol.toPrimitive](): number {
        return 1;
    }
}

var x = ['a','b','c'];
var f = new Foo();
x[f];

We give the error an index expression argument must be of type ... on the array access.

Foo is for all intents and purposes a wrapper around the number 1 (close to new Number(1)), yet it cannot be used to index an array, since Foo itself is not of type number, string, symbol, or any. We could do extra type-checking to see if an object has a user-defined Symbol.toPrimitive and consider its return types when checking type-coercing operations (after all, if you've opted in to using Symbol.toPrimitve it's probably part of your goal to gain this behavior), such as indexing or mathematics operators.

Building on this, we currently don't support the coercion of Number or String classes to their respective primitive types (which are a specialization of the above issue but which applies to ES5 and ES3 output). Presently one can't do this:

function add(a: string, b: string): number {
  var x = new Number(a);
  var y = new Number(b);
  return x + y;
}
add('10e4', '0x8');

Because since neither x nor y is the 'number' (or 'string') primitive type, the addition operation is not allowed. Though it's still valid js (and without the usage of the Number class, the addition would result in '10e40x8'!).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the index-expression and addition examples in the issue, then trace the type-checking rules for index arguments and arithmetic operands. Done means consistently accounting for Symbol.toPrimitive and Number/String wrapper coercion without allowing invalid operations.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.