TypeScript: Add related error spans for getter/setters with different types

Now that we support multiple related spans for errors (#10489, #22789, #24548), we’d like to improve an existing error message.

Currently, we provide a diagnostic for a pair of get/set accessor’s types not matching:

Code:

let x = {
  get foo() { return 100; }
  set foo(value: string): { }
}

Current error:

'get' and 'set' accessor must have the same type.

We’d like to give a better error message. For example:

Primary span:

A 'get-' and 'set-' accessor must have the same type, but this 'get' accessor has the type '{0}'.

Related span:

The respective 'set' accessor has the type '{0}'.

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Comments: 17 (7 by maintainers)

Commits related to this issue

Most upvoted comments

setters and getters MAY HAVE different types

image

get zIndex(): string
set zIndex(value: string | number | null | undefined)

Another example:

class MY_URL {
    get query(): Record<string, string>
    set query(value: string | Record<string, string | number | null |undefined>);
}

const url = new MY_URL();
url.query = "foo=1&bar=2" // string setter
url.query = {foo: 1, bar: "2"} // Record<string, ...> setter

assert("1" === url.query.foo && "2" === url.query.bar)

@RyanCavanaugh

There is no restriction on get set in ECMA specification, so adhering to the standard, shouldn’t this restriction be lifted? I mean “‘get’ and ‘set’ accessor must have the same type”.

I completely agree with @acagastya and @sirian. Different setters/getters are very useful when doing normalization.

/cc @sindresorhus