How can I narrow the type output of a factory create method using literal types? I've tried narrowing with if statements and discriminated unions, but since this is a creational method, I'm not sure if it's possible.
class Radio {
type: "RADIO"; // literal type
title: string = "A value";
selected: boolean = false;
constructor(radio?: Radio) {
}
}
class OptionFactory {
static create({
type,
price = 1.0,
title = "Option",
selected = false,
}: {
price: number;
title: string;
selected: boolean;
}) {
switch (type) {
case "RADIO":
return new Radio({
title,
selected,
// price,
});
case "CHECKBOX":
return new Checkbox({
title,
selected,
// price,
});
case "PRICEOPTION":
return new PriceOption({
title,
selected,
price,
});
}
}
}
let radioButtons = new Array<Radio>();
tags.push(OptionFactory.create({ type: "RADIO" })); //error ts(2345)
console.log(tags);
Typescript Playground