microsoft / microsoft/TypeScript

Suggestion: Upper-bound generic type constraints

Abierto
#9,252 9 comentarios 28 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

This is a proposal for generic structural supertype constraints.

I'll first detail the proposal, and then get into a discussion about use-cases.

Proposal

A supertype constraint is a constraint on a generic type parameter to be the structural supertype of another type. It's like a subtype/inheritance constraint, but from the other direction. For example, let's say we have a square:

interface Square {width : number; height : number}

In this suggested syntax, you could write:

performAction<T extended by Square>(partialSquare : T) {}

This means the type T must be a structural supertype of square. So the potential candidates for T are:

{width : number}, {height : number}, Square, {}

It's an established kind of type constraint, not something I just made up. Although it's not exactly common, some languages do implement this feature, such as Scala. In Scala, you can write:

def performAction[T >: Square](obj : T) = { ... }

To express a supertype/upper bound constraint. In this case, of course, the constraint isn't structural -- T must declare that it implements Square.

Utility

In most languages, including Scala, this kind of constraint isn't very useful. It only comes up in certain specific situations.

However, Javascript libraries often have this kind of API, where you're allowed to specify the partial properties of an object to modify it (the rest remain at their previous value).

In many cases, you can support this by having optional interface members, but isn't always possible or correct.

An important example is React, which defines a method called setState:

class Component {
    var state;

    setState(partialState) {
        //merges the properties of partialState with the current state.
    }
}

The right signature for this method should be:

class Component<Props, State> {
    setState<PartialState extended by State>(partialState : PartialState) {
        //merges the properties of partialState with the current state.
    }
}

Currently,the definition files state that it is:

setState(fullState : State) {
    //merges the properties of partialState with the current state.
}

Which doesn't fully capture the functionality of the method.

Notes

The suggested syntax doesn't give us a nice way of combining both subtype and supertype constraints. One possibility is:

exampleMethod<T extends LowerBound and extended by UpperBound>

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

El issue no proporciona ningún archivo, prueba ni punto de entrada de implementación; comienza leyendo la propuesta y su ejemplo de React setState, y después localiza en el repositorio las áreas relacionadas con las restricciones genéricas y la comprobación de tipos. Para darlo por terminado sería necesario acordar la sintaxis y la semántica de las restricciones de supertipo estructural, incluida su interacción con los límites inferiores, pero el issue no define esos detalles.

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
Bastante claro
Aptitud para principiantes
20/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.