microsoft / microsoft/TypeScript

Generic of abstract class should be inferrable from abstract property implemented in subclass

Abierto
#39,180 11 comentarios 9 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
1 d 19 h
PR fusionados (30 d)
117

Descripción

Search Terms

  • generic
  • abstract class
  • abstract property
  • type inference

Suggestion, Use Case and Examples

As of typescript 3.9.3, if I write a code like the following:

abstract class SomeMapper<T extends string> {
    private someMap = new Map<number, T>();
    protected abstract readonly rndText: T;

    getSome(num: number) {
        return this.someMap.get(num)!;
    }
}

function rndGender(): 'male' | 'female' {
    return Math.random() > 0.5 ? 'male' : 'female';
}

class Gender extends SomeMapper<'male' | 'female' /* need to provide this explicitly */> {
    readonly rndText = rndGender();

    constructor() {
        super();
    }
}

const gen = new Gender();
const some = gen.getSome(1);

I have to make sure I always provide the generic to the SomeMapper class, and if I ever update the type of rndText in Gender class, I'll have to go and update the generic as well every time. The only way as of now to make this kinda auto-infer the generic, is to write it like this:

class Gender extends SomeMapper<Gender['rndText']> {
    readonly rndText = rndGender();

    constructor() {
        super();
    }
}

However this is not the most elegant way and can get very dirty with complicated type (for example check this), and typescript should be able to do this on its own, similar to what it does with generics in functions.

So the ideal behaviour should be simply like this:

// Below line should not error: Generic type 'SomeMapper<T>' requires 1 type argument(s).
// Should auto infer the generic from property rndText
class Gender extends SomeMapper {
    readonly rndText = rndGender();

    constructor() {
        super();
    }
}

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

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 reproducción en TypeScript del issue y compara la forma genérica explícita con la forma propuesta class Gender extends SomeMapper. Se considera terminado cuando la declaración propuesta supera la comprobación de tipos e infiere el genérico a partir de la propiedad abstracta implementada, sin requerir un argumento de tipo explícito.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.