microsoft / microsoft/TypeScript

Feature Request: access inherited protected member in subclasses branched from a base class where the protected member is defined in the base class

Abierto
#30,756 1 comentario 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Search Terms

  • typescript protected class branch
  • typescript access protected in sibling

Suggestion

Allow subclasses to access inherited protected members across instances of the subclasses.

Use Cases

There are use cases when we'd like subclass branches that inherit a protected member to be able to access the inherited protected member across instances of the branched subclasses.

There are also use cases where subclasses cause invariants by narrowing the type of an inherited member, which we should be able to guard against at compile time.

Examples

This PlayGround example doesn't work, to illustrate the current limitation.

I have a use case, where I have a TreeNode sort of class with protected properties, then I have subclasses of the TreeNode, one called Mesh, and the other called Scene, where the Scene needs to traverse the tree to run logic using the protected members (thus reading the protected member of all instances of Mesh), but TypeScript won't allow it.

The code that is Scene-specific lives inside the Scene class (because that makes sense).

To make it work, I'd have to move that code into the common base class TreeNode, but then it will be messy and un-organized.

FWIW, I have the same problem in my runtime JS class implementation, lowclass, which I'm now thinking about solving with an option.

In general, I think that well-designed classes will benefit from this feature, and that poor coding practices will lead to issues with this (which is why the compiler should catch the problems in those cases). (f.e. if base class specifies a protected member of type number | string, and a sibling subclass changes it to number, then the compiler can obviously catch a problem when another sibling subclass wants to read from the other one and hasn't narrowed the type to number as well.)

implementation ideas

A subset of the following ideas might do the trick:

  • a compiler option to allow or disallow this feature

  • We can detect invariants at compile time. From this post,

    Other sibling classes might add invariants that your class doesn't know about

    In the above example, if the types agree in the subclasses, we can let it work, and throw a runtime error only when there is a type mismatch. But suppose in my above example that Scene and Mesh don't modify the inherited protected type, and only read it or set it. The compiler can easily ensure that things are okay.

  • disallow subclasses from modifying types of inherited members

    • perhaps a compiler option for this
    • this can prevent subclasses of subclasses of subclasses from being so far removed (not resembling their base class at all), by forcing subclasses to add new features on new properties instead of existing ones
  • Follow the same rules as public, which is not guarded against this. An invariant problem can happen across siblings inheriting and modifying the member from the base class, yet the compiler will not stop it.

  • another compiler option

Mainly, my reasoning above is that there is a way to make this work with some semantics and/or options, and it is okay if those are specific to TypeScript. We won't invent new wheels, but we can improve existing wheels instead of copying them.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code not sure
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Related Issues:

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza revisando las issues relacionadas enlazadas y los ejemplos de Playground para entender las reglas existentes de protected members y la semántica propuesta para el acceso entre clases hermanas. Una contribución completa requeriría un diseño acordado, un comportamiento documentado de la comprobación de tipos y pruebas que cubran los casos de herencia y narrowing descritos aquí.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
20/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.