Skip to content

Type inference incorrectly considers const z = { ...this } to be z: this #62154

@DayKev

Description

@DayKev

🔎 Search Terms

class
this
object spread syntax
type inference

🕗 Version & Regression Information

The issue occurs in 5.8.3, as well as the oldest version the Playground supports (3.3.3) and the current nightly version in the Playground.

⏯ Playground Link

https://www.typescriptlang.org/play/?target=10&module=7&ts=5.8.3#code/MYGwhgzhAEAuCmFbQN4ChrQA4FcBGIAlsNAGaHwgAmAggFzQB2OAtnvAE4DcG2+RJcpSoAhBszacevYAHtGSDjmCxZHABRhxrdhwA00PNskcAlKl6ZYAC0IQAdEOo1oAXmhgemK7YdPRboZe0AC+aLy4BMQe6qbGuhbe0BzwsDgcjNAAjMFhEfzRhCxYHLJYnACSjKSc8IzA8LGJ3gD0LdBFJWWcIACeHdWcKVRwsobw0AAGNnaTltByCsgAXoEo0PabMzAh0kkpaRnQy7nhmJEC2KXlHFU1KfWN5uhJi0jQAI6BjPAA7nCIWDqLIGABMpmCmDaV26HD6A3uw1G4ym6389CYOikZAo1DEmJMXFCc1e8neq3c6029nU2w8MFgvXKslIn3MuzO3gO6UyJ14YRCQA

💻 Code

class test {
  public fieldA: number;
  public fieldB: number;

  constructor(a: number, b: number) {
    this.fieldA = a;
    this.fieldB = b;
  }

  public a(): number {
    return 1;
  }

  public improperInference() {
    // improperly inferred to be `this`
    const z = { ...this };

    return z;
  }

  public properInference() {
    const q = new test(1, 2);
    // properly inferred to be `{ fieldA: number; fieldB: number; }`
    const z = { ...(this as typeof q) };

    return z;
  }
}

🙁 Actual behavior

const z = { ...this } is inferred to be this

🙂 Expected behavior

const z = { ...this } should be inferred to be a POJO with fields matching the public fields of the class.
(Actually it should also infer the protected and private fields. They're accessible from this and so should be visible at this point.)

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions