Skip to content

Infer type when object coerced to string if toString explicitly defined #35945

Open

Description

Search Terms

coercion toString computed properties

Suggestion

Infer type when object coerced to string if toString explicitly defined

Examples

Would be nice if the following would be allowed

const action = {
  type: 'foo',
  toString() { return this.type }
} as const;

const reducerHandler = {
  [action]: () => { } // Currently errors: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
}

Playground

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Activity

  1. changed the title [-]Infer type when object coerced to string if `toString` explicitly defined[/-] [+]Infer type when object coerced to string if toString explicitly defined[/+] on Jan 1, 2020
  2. rihok commented on Aug 27, 2020

    @rihok

    I think this would definitely be useful.

    As it stands today, TS doesn't really allow for explicit toString, which in some sense makes it incompatible with regular JS. Unless you give up pretty much all type safety for a given value. Adding { toString(): string } to your types essentially means you accept everything. I'm not sure if automatically accepting toString where string literal is expected would be a good idea, however a way to specific that explicit toString is accepted, would help with many different cases use-cases.

  3. isometriq commented on Jun 15, 2021

    @isometriq

    for this to work safely, would require to instruct the compiler with a type like string | { toString(): string }, or somehow a new conventional type like tostring ? serializable, stringprovider, etc...

    class ComplexObject {
      toString() {
        return 'serialized-value';
      }
    }
    
    type tostring = string | { toString(): string };
    
    function doSomething1(value: string | { toString(): string }) {;}
    function doSomething2(value: tostring) {;}
    
    const obj = new ComplexObject();
    doSomething1(obj);
    doSomething2(obj);
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

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions