Tengo una pregunta quizás trivial, pero no puedo entender cómo puedo usar los métodos de una clase abstracta basada solo en llamarla y elegir la anulación correcta según el tipo de valor que tengo como entrada.
Por ejemplo, si tengo algo como esto:
export abstract class Parent { constructor( public type: View ){} abstract getSource(): string | string[] } export class Child1 extends Parent { getSource(): string { return this.type.view1 } } export class Child2 extends Parent { getSource(): string[] { return this.type.view2 } }Y quería llamar a la clase abstracta Parent y, según el tipo, averiguar si usar la función en la clase Child1 o Child2. Pensé que podrías hacerlo así:
export class AngularComponent { public _VieweSource: string | string[]; @Input() set data(type: View) { // here i need to return Child1.getSource() or Child2.getSource() // not calling new Child1(type).getSource() // but something like this: Parent(type).getSource() --> Child1 if type.view1=string || Child2 if type.view2=string[] } } el tipo de View es este:
{type: "simple", view1: "hello world"} || {type: "complex", view2:["hello", "world"]}Lo siento si la pregunta es incorrecta, si hay alguna pregunta puedo responder. Gracias por adelantado.
El problema es que está tratando de elegir qué clase usar, según los valores en type . No debe intentar dejar que la herencia decida qué clase elegir, se crea una declaración if simple para eso.
export class AngularComponent { public _VieweSource: string | string[]; @Input() set data(type: View) { let obj: Parent; if (type.view1 && typeof type.view1 === 'string'){ obj = new Child1(type); } else if(type.view2 && type.view2 instanceof Array){ obj = new Child2(type); } obj.getSource(); } }