Skip to content

Confusing error message (2322), should use (2741) and (2322) error message when this["XXX"] = {...} has a missing (or mispelled) key or an incompatible value.Β #63206

@denis-migdal

Description

@denis-migdal

πŸ” Search Terms

Relevant issues:

βœ… Viability Checklist

⭐ Suggestion

When we have a Record this["faa"] to which we affect an object with an incompatible type, e.g.:

  • a key is missing (or misspelled).
  • one value has the wrong type.

The following error is shown:

Type '{}' is not assignable to type 'this["faa"]'.
'this["faa"]' could be instantiated with an arbitrary type which could be unrelated to '{}'.(2322)
input.tsx(3, 19): 'key' is declared here.

In this context, I'd like the error message to be modified in order to be less confusing, i.e. :

  • if a key is missing: "Property 'key' is missing in type '{}' but required in type '{ key: number | null; }'.(2741)"
  • if one value has a wrong type: "Type 'string' is not assignable to type 'number'.(2322)".

πŸ“ƒ Motivating Example

Playground Link

class A {
    declare foo: this["faa"];
    declare faa: {key: number|null}

    fuu() {
        // Type '{}' is not assignable to type 'this["faa"]'.
        // 'this["faa"]' could be instantiated with an arbitrary type which could be unrelated to '{}'.(2322)
        // input.tsx(3, 19): 'key' is declared here.
        this.foo = {} 

        // Type '{ key: string; }' is not assignable to type 'this["faa"]'.
        //   'this["faa"]' could be instantiated with an arbitrary type which could be unrelated to '{ key: string; }'.(2322)
        this.foo = {key: "str"}

        this.foo = {key: 42} // ok
    }
}

let foo: {key: number|null};

// Property 'key' is missing in type '{}' but required in type '{ key: number | null; }'.(2741)
// input.tsx(12, 11): 'key' is declared here.
foo = {}

// Type 'string' is not assignable to type 'number'.(2322)
// input.tsx(12, 11): The expected type comes from property 'key' which is declared here on type '{ key: number | null; }'
foo = {key: "str"}

foo = {key: 42} // ok

It is easy to forget a key or to misspell it. Unfortunately, the error message is currently confusing.

When playing with this["faa"] we often encounter this error, and we might look at it too quickly, missing (or misunderstanding) the last line, thinking this is some kind of TS limitation.

πŸ’» Use Cases

  1. What do you want to use this for?

Having more explicit error messages.

  1. What shortcomings exist with current approaches?

Confusing error message.

  1. What workarounds are you using in the meantime?

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions