tgmlDoc.createElement(tagName)
typically returns objects of type any
. I am looking to refine the return type in the function below in order to simplify the rest of my code. Is there a way to accomplish this? My attempt is shown below, but unfortunately, the return type remains as TgmlTgml | TgmlLayer | null
no matter what tagName is passed to the function. Ideally, I would like it to be TgmlTgml | null
if tagName 'tgml' is passed and TgmlLayer | null
if tagName 'layer' is passed.
export function createElementIfAllowed(tagName: string, parent: TgmlDocument | TgmlElement) {
if (!allowedInParent(tagName, parent)) {
return null;
}
const tgmlDoc = parent.ownerDocument || parent;
const child = tgmlDoc.createElement(tagName);
// Narrowing down the types from any
if (child instanceof TgmlTgml) {
return child;
} else if (child instanceof TgmlLayer) {
return child;
} else {
throw new Error(`TGML Element with tagname ${tagName} not allowed`);
}
}