microsoft / microsoft/TypeScript

Allow for entire interface definitions to be marked "readonly"

Abierto
#45,535 3 comentarios 8 reacciones 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

Suggestion

Just interfaces. I wanted to request this specifically since it touches a lot of other things that are under discussion in the issue history here.

🔍 Search Terms

https://github.com/microsoft/TypeScript/issues/10725#issuecomment-308855915

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

From the search term linked to above:


I would like to be able to do something like this:

readonly interface Foo {
  one: string
  two: string
}

It could be a deep readonly, but I would be ok with it being shallow. Ultimately I'm trying to avoid doing this:

interface Foo {
  readonly one: string
  readonly two: string
}

If someone adds another property, it may not be clear that Foo is supposed to be treated as an immutable type.


👏 Interfaces individually should be marked readonly, any extending of it must designate those restrictions themselves. More in use cases.

📃 Motivating Example

Python's frozen dataclasses, with better guarantees

💻 Use Cases

In the effort to strike a good balance between "immutable" typescript and productivity payolffs, I would suggest two options: atomic readonly interfaces (nothing other than that exact interface is readonly) as well as persistent readonly interfaces (like the kinds you get with an ORM).

An atomic readonly interface is bounded to just the one interface, but without marking itself as persistent only other references remain readonly. This is the default.

readonly interface B {
  thisWillNotChange: string;
  evenIfReferencedElsewhere: string; 
}

interface A {
  foo: string;
  bar: number;
  interfaceB: B;  // error: reference to readonly interface `B` must be accessed via a readonly property
  mutableB: abstract B; // ok
}

interface C extends B {
  mutableProperty: string;
}

class Thing implements C {
    // ....
}

thing = new Thing(...foo);
thing.mutableProperty = "other";  // ok
thing.thisWillNotChange = "";  // not ok

An interface which needs mutable properties in B would still be able to do so, with an "abstract override".

interface C extends abstract B {
  // ...
}

readonly interface D extends abstract B {
  // properties defined by B are mutable, all properties in D are readonly.
};

This abstract interface pattern can be used to define a stricter "deep" readonly behavior.

abstract readonly interface ORMData {};

interface ExampleServiceData extends ORMData {
  // error: interface 'ExampleServiceData' must be readonly to extend abstract readonly interface ORMData
};

interface ExampleServiceMetadata extends ExampleServiceData {
  // error: interface 'ExampleServiceMetadata' must be readonly to extend abstract readonly interface ORMData
};

Going all out this way gets you the ability to generate warnings/reports of abstract interface usage (and importantly, overrides of those interfaces), as well as any references that appear later on where this override was actually used.

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 con la discusión vinculada de la issue de TypeScript y los objetivos de diseño del repositorio; aquí no se nombran archivos de implementación, tests ni puntos de entrada. Antes de la implementación, aclara si la funcionalidad es superficial o profunda y cómo deben interactuar readonly, abstract, la herencia y las referencias. La finalización requiere que esa semántica esté acordada y cubierta por tests.

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
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.