I'm currently exploring the intricacies of type inference rules, and I've encountered a challenging scenario:
Here's the scenario:
interface Model{
label?: string;
}
interface View<T>{
cid?: string;
model?: T;
}
class Foo {
findWithModel<TModel extends Model, TView extends View<TModel>>(value: TModel): TView;
findWithModel(value: string): any {
return {cid: "2"};
}
}
class AModel implements Model{
constructor(public label: string){}
}
class AView<T extends Model> implements View<T>{
cid = "1";
model = null;
}
let f = new Foo();
let model = new AModel("test");
Essentially, I have an overload called findWithModel
, where in one case it returns any
and in another case it should return something like SomeView<SomeModel>
. The problem arises when trying to achieve this as follows:
let trial1 = f.findWithModel<AView<AModel>, AModel>(model);
let trial2: AView<AModel> = f.findWithModel(model);
The first trial works fine but appears overly verbose. It feels redundant to pass AModel
twice.
My assumption led me to believe that I should only provide type information in the result declaration for trial2
, however, typescript interprets it as:
Foo.findWithModel<AModel, {}>(value: AModel): {}
This obviously results in an error:
Property 'cid' is missing in type '{}'
Is there a way to achieve this without using the excessively verbose method of passing AModel
twice?