TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Generic type inference breaks when deriving from generic type

Open rwyborn opened this issue 11 years ago • 2 comments

I have found a simple case where generic type inference breaks when you have a type derived from a generic type.

declare class BaseData<Schema> { }

declare class Widget<Schema> {
    constructor(data: BaseData<Schema>);
    default(): Schema;
}

declare interface DataSchema {
    name: string;
}
declare class ExtendedData extends BaseData<DataSchema > { }

function test() {
    let widgetWithBaseData = new Widget(new BaseData<DataSchema>());
    // OK. Intellisense shows widgetWithBaseData as type Widget<DataSchema>
    console.log(widgetWithBaseData.default().name);

    let widgetWithExtendedData = new Widget(new ExtendedData());
    // Compile error. Intellisense shows widgetWithExtendedData as type Widget<{}>
    console.log(widgetWithExtendedData.default().name);
}

Note that for simplicity the example code uses ambient declarations, but the same issue also occurs with concrete implementations.

rwyborn avatar Oct 01 '15 01:10 rwyborn

This is by design. The problem is that BaseData never actually uses the Schema type parameter in a member. Thus, when inferring from ExtendedData (the type of your argument) to BaseData<Schema> (the type of the parameter), there is nothing to infer from and we end up with {}. If you add a member to BaseData that actually uses Schema (e.g. x: Schema) it all works as expected.

ahejlsberg avatar Oct 01 '15 13:10 ahejlsberg

I should add that the reason this breaks with a derived class is that when inferring from references to different types (in this case ExtendedData and BaseData<Schema>), we make the inferences structurally, i.e. by relating the members of the two types. However, when inferring from references to the same type (e.g. BaseData<DataSchema> and BaseData<Schema>) we can simply infer by relating the type argument to the type parameter. Thus, it works without members in that case.

ahejlsberg avatar Oct 01 '15 13:10 ahejlsberg