Issue
Is it possible to infer types from a generic class?
In the example below I'd like to infer the types in the Component class to get the type and the value:
class Obj<T,V>{
constructor(type: T, value: V){
this.type = type;
this.value = value;
}
type: T
value: V
}
class TextObj extends Obj<"text" | "email", string>{
}
class Component<O extends Obj<infer F, infer V>> {
constructor(obj: O){
this.obj = obj;
}
obj: O
getValue():V {
return this.obj.value;
}
getType():F {
return this.obj.type;
}
}
class TextComponent extends Component<TextObj>{
}
let txtComp = new TextComponent(new TextObj("text", "some Text"));
let value = txtComp.getValue();
//^--- should be string
Solution
Instead of trying to infer type variables like this, you can access them indirectly. Since both are conveniently exposed as property types, you can use item access syntax:
class Component<O extends Obj<unknown, unknown>> {
constructor(obj: O) {
this.obj = obj;
}
obj: O
getValue(): O['value'] {
return this.obj.value;
}
getType(): O['type'] {
return this.obj.type;
}
}
Answered By - STerliakov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.