Skip to content

Support 'did you mean' for assignments to unions with string literals #45679

@orta

Description

@orta

Suggestion

type A = "abc" | "abcd" | "abcde";
const a: A = "abb";
// Type '"abb"' is not assignable to type 'A'.

Could instead be:

type A = "abc" | "abcd" | "abcde";
const a: A = "abb";
// Type '"abb"' is not assignable to type 'A'.
//   Did you mean "abc"?

🔍 Search Terms

did you mean literals unions assignment

✅ Viability 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

📃 Motivating Example

If we already know all/a set of the possible entries, it can't hurt to see if any are close enough and try recommend them like we do in other places.

My actual case was this:

src/compiler/commandLineParser.ts:1088:13 - error TS2322: Type '"strong"' is not assignable to type '"string" | "number" | "boolean" | "object" | ESMap<string, string | number> | "list"'.

1088             type: "strong",
                 ~~~~

  src/compiler/types.ts:6272:9
    6272         type: "string" | "number" | "boolean";
                 ~~~~
    The expected type comes from property 'type' which is declared here on type 'CommandLineOption'

Where we know a set of literals and a non-literal are possible, and as I was very close to one I figured TS would have enough knowledge to offer the case for what the typo probably is.

💻 Use Cases

Just dev workflow stuff.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: Error MessagesThe issue relates to error messagingEffort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Help WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions