microsoft / microsoft/TypeScript

Could there be a `This` type like the `Self` type in rust ?

Abierto
#44,055 7 comentarios 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

Suggestion

🔍 Search Terms

This, Self, typeof this

✅ 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

For example, let's declare an interface Cloneable, instances of classes implementing Cloneable should be able to clone themselves:

interface Cloneable {
    clone(): This
}

The return type of function clone() of interface Cloneable should be the actual type of this, or typeof this in the shown code. However typeof this does not work. It will raise TS2304 Cannot find name 'this', and TS4055 Return type of public method from exported class has or is using private name 'this'.

clone(): Cloneable is not the desired way for this interface, or the below code would pass type check:

class A implements Cloneable {
    clone() { return new B() }
}
class B implements Cloneable {
    clone() { return new A() }
}

Besides, clone() is not returning this. So clone(): this is not the right way to go. It won't allow this to pass:

class A implements Cloneable {
    clone() { return new A(this)  }
}

Generics could be a workaround, but it can be annoying for complex cases, and still can be a problem:

class A implements Cloneable<B> {
    clone() { return new B() }
}

It does not make any sense to have sth like class A implements Cloneable<B>, but generics allows it.

Allowing typeof this, or This, could be a very useful in that case.

This feature could also help in some other cases, like interface Addable:

interface Addable {
    add(that: This): This
}

The argument that of function add must be of the same type of this, so it cannot be declared as add(that: Addable): Addable. It also cannot be add(that: this): this.
It makes sense to use generics,

interface Addable<That> {
    add(that: That): That
}

But still, it is not a very good way.

📃 Motivating Example

💻 Use Cases

As discussed above, it is mainly used by interfaces and abstract classes, like interface Cloneable, interface Addable, or maybe interface Serializable and interface Serializer.
The current approaches cannot provide the correct behavior, which is discussed above.
I am using generics, but it is incorrect indeed.

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 menciona archivos ni pruebas del repositorio. Empieza revisando el comportamiento existente del tipo this y los objetivos de diseño de TypeScript referenciados en el issue; después compara los ejemplos de Cloneable y Addable con sus soluciones alternativas genéricas; para darlo por terminado harían falta una semántica definida y un plan de implementación para el tipo propuesto.

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
Bien especificado
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.