microsoft / microsoft/TypeScript

Private class field helpers throw a confusing error when in unbound method with undefined `this`

Open
#57,609 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

this undefined bind private identifier class __classPrivateFieldSet __classPrivateFieldGet bound unbound

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

https://www.typescriptlang.org/play?#code/MYGwhgzhAEBiD29oG8BQ0PQMQDcwgFcBTaAXmgEYAmAZgBYBudTAcyIBcA1fYgCgEoU0AE4cCwgHbR2ACwCWEAHS4eRBtAC+qLamDwJEdtABmiMtAlEA7nEQCmu-RHggiikPBa8ABqfiK2LlUBcwASZD8Ajm5CIgENb34HAHpk6AB5eAAHCAAaaABJaAATOWKJAHIjACM5CWKAQkcDI0CY4nNIttUUtIAVGWF4KwgALmgAYTAJCXgjUTBi6CzhOTx2EgBbIk3qomETIc3oaeh4aoArImAjKxl4CBJQSBhSpdmjYuvwUWg5dmazlc7k8Pm6sRC5HC4L4-AS-FQQA

💻 Code
class Foo {
    #value = 1234;
    getValue() { return this.#value; }
}

const foo = new Foo();

console.log(`foo.getValue() = ${foo.getValue()}`);

// Oops, I didn't bind!
const getValue = foo.getValue;

// Throws: Cannot read private member from an object whose class did not declare it
console.log(`getValue() = ${getValue()}`)

🙁 Actual behavior

Throws Cannot read private member from an object whose class did not declare it.

But the actual problem is that this is undefined and I had no idea!

🙂 Expected behavior

A special error for this when undefined; IIRC there's no possible way this would normally pass, so a special error would be a lot more clear.

Additional information about the issue

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the unbound private-field access in the linked TypeScript Playground and compare it with the bound call shown in the issue. Trace how the compiler's generated private-field helper reports the failure, then make the undefined-this case produce the clearer error described and verify both examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.