microsoft / microsoft/TypeScript

Make it possible to infer superclass type parameters / constructor overload from the `super` call

Abierto
#36,456 14 comentarios 37 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

Search Terms

superclass base class generic type infer contextual infer parent generic super constructor

Suggestion

Make it possible to infer superclass type parameters / constructor overload from the super call

Use Cases

I'm working on an intermediate library with typings for a legacy codebase. That intermediate library is used in third party to use the functionality from the main codebase (called adapters). There are several supported ways to access this functionality:

  1. const foo1 = Adapter(options);
  2. const foo2 = new Adapter(options);
  3. class Foo3 extends Adapter { ... } - The constructor must call the superclass constructor with the options.

Now the problem is that the Adapter "class" (actually an ES5-style "function" class) has some properties that only exist if specific options are passed to its constructor. I'm able to model this behavior for case 1 and 2, but not 3 - at least not without manually specifying the type.

Here's what I have so far. The code is split into three parts: main codebase, intermediate library, 3rd party / user code. (Playground link)

// legacy code, cannot change:
declare class InternalAdapter {
    // actually an ES5-style class function, can be called with and without new!
    someProp1: any;
    someProp2: any;

    // I want to override this type
    cacheObj: Record<string, any> | undefined;
}

// ========================

// My code, can change:
interface AdapterOptions {
    name: string;
    cache?: boolean;
}

type AdapterInstance<T extends AdapterOptions> = T extends {
	cache: true;
}
	? Omit<InternalAdapter, "cacheObj"> & {
			cacheObj: Exclude<InternalAdapter["cacheObj"], undefined>;
	  }
	: Omit<InternalAdapter, "cacheObj">;

interface AdapterConstructor {
	new (adapterName: string): AdapterInstance<{name: string}>;
	new <T extends AdapterOptions>(adapterOptions: T): AdapterInstance<T>;
    
	(adapterName: string): AdapterInstance<{name: string}>;
	<T extends AdapterOptions>(adapterOptions: T): AdapterInstance<T>;
}

declare const Adapter: AdapterConstructor;

// ========================

// User code, should be as simple as possible
const name = "foobar";
const options = { name };

const test1 = Adapter(name);
test1.cacheObj; // does not exist, expected

const test2 = new Adapter(name);
test2.cacheObj; // does not exist, expected

const test3 = Adapter(options);
test3.cacheObj; // does not exist, expected

const test4 = new Adapter(options);
test4.cacheObj; // does not exist, expected

const test5 = new Adapter({ ...options, cache: true });
test5.cacheObj; // exists, expected

// Here, the problems start:

class Test6 extends Adapter<AdapterOptions> {
    constructor(options: AdapterOptions) {
        super(options);
        this.cacheObj; // does not exist, expected
    }
}

class Test7 extends Adapter<AdapterOptions> {
    constructor(options: AdapterOptions) {
        super({ ...options, cache: true });
        this.cacheObj; // does not exist, unexpected
    }
}

class Test8 extends Adapter<AdapterOptions & {cache: true}> {
    constructor(options: AdapterOptions) {
        super({ ...options, cache: true });
        this.cacheObj; // exists, but I have to duplicate the type
    }
}

Notice how the class definitions are all awkward. In Test6 I have to duplicate the generic type AdapterOptions or the super call will default to the string constructor.
In Test7 this is actually wrong, because the generic type overrides the conditional behavior for the cacheObj. This can be fixed like in Test8, but that is really ugly. IMO, TypeScript should be able to infer the type arguments from a constructor call if that type argument matches the class' type argument

Examples

Show how this would be used and what the behavior would be - Ideally it should be like this:

class Test9 extends Adapter {
    constructor(options: AdapterOptions) {
        super({ ...options, cache: true });
        this.cacheObj; // should exist
    }
}

The super call would be used to infer that the 2nd constructor overload is the correct one:

new <T extends AdapterOptions>(adapterOptions: T): AdapterInstance<T>;

and therefore the instance type would be AdapterInstance<AdapterOptions & {cache: true}>.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code (not sure actually. I'd guess not?)
  • 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 el TypeScript Playground enlazado y compara los ejemplos Test6–Test9, centrándote en cómo la llamada a super selecciona una sobrecarga del constructor y determina el tipo de instancia de la subclase. Se considera terminado cuando la forma deseada de Test9 infiere el tipo de options a partir de super({ ...options, cache: true }), de modo que cacheObj esté disponible sin duplicar el tipo genérico.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.