microsoft / microsoft/TypeScript

emit an error when using #private fields in their "temporal dead zone"

Open
#56,810 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

🔍 Search Terms

error for private member accessed before ready

✅ Viability Checklist
⭐ Suggestion

This produces a runtime error when you run it:

abstract class Base {
  constructor() {
	this.createStuff()
  }

	abstract createStuff(): void
}

class Sub extends Base {
	#makeSomething() {
		console.log('make stuff')
	}

	createStuff() {
		this.#makeSomething()
	}
}

// TypeError: Cannot read private member from an object whose class did
// not declare it (JavaScript points finger at you while laughing)
new Sub().createStuff()

playground

📃 Motivating Example

It has happened to me too many times due to subclass code running early before initialization of private fields.

Unfortunately the simple solution is to avoid class fields for this case (use properties-defined-in-constructor, or getters).

💻 Use Cases

Sometimes we want a constructor to make stuff generically for subclasses, but then subclasses should override or implement some methods to replace certain parts.

I believe there is enough static info that it would be possible to check for this case and emit a compile error.

Similarly it would also be possible to enforce non-private fields to be | undefined when used early in a location that is known to be called before initialization (f.e. in a superclass constructor).

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

Reproduce the subclass example in the linked TypeScript Playground and compare its runtime failure with the requested compile-time diagnostic. Determine the intended scope for superclass-constructor access to private and non-private fields, then define tests that confirm the relevant early-use cases are rejected without changing emitted JavaScript.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.