Skip to content

private fields in nested classes should have separate types?Β #60882

Open
@trusktr

Description

πŸ” Search Terms

typescript private field nested class

βœ… Viability Checklist

⭐ Suggestion

Private fields of a wrapper class are similar to symbols: perhaps the nested classes could have their own types for the fields based on the value they initialize in their constructor:

πŸ“ƒ Motivating Example

https://www.typescriptlang.org/play/?noImplicitAny=false#code/MYGwhgzhAEBiBOBLApgOwCYwN4CgCQAxAG5ggCuyO+sA9jdALzSiQy33IAeALmpnEj7Z8eYDVQRu8MsG414ACgCU0XHnUQyAB2SKlIvNwAWiCADpipCo2gAWAKwA2aAHoX0ADwBaH779foVDIAWwAjXREAXyp1ADM6AFlkYxp0ZVUDMQkaEGQzEBoAcwVjUwsScmR9dWi8aPwAITB4GxYoaCaWrl4MGFLzdgz1LMlpWXl0tQ1tXWUDfvKrZBsAIgB2AA4AThXXd29-Q59oUcRUQqiYvFDmpJS0lSnRcQgcvILihctK6rr8aPqI24qnYABoOs1IjZUMgAO4CFC9OY4IHQWLQuFwOhzVGhDHwzrI2JmeI0O5GVLpNzQD4wFYORwrHChMw3eDkykqam06DrbYrIA

Plain JS:

class Friends {
	#priv

	Foo = class Foo extends Friends {
		constructor() {
			super()
			this.#priv = 456 // <----------- number
		}

		fooMethod() {
			console.log(this.#priv)
		}
	}

	Bar = class Bar extends this.Foo {
		constructor() {
			super()
			this.#priv = "789" // <-------------- string
		}

		barMethod() {
			console.log(this.#priv)
		}
	}
}

const {Foo, Bar} = new Friends()

const f = new Foo()
const b = new Bar()

f.fooMethod() // logs "456"
b.barMethod() // logs "789"

πŸ’» Use Cases

Allows having a "private" key to use on multiple classes, but each class could have a different type of value.

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions