Apologies for the unclear title, I'm struggling to articulate my question effectively. Currently, I am attempting to create a method that can parse an object from an XML file. The XML structure (translated to JavaScript using xml-js) appears as follows:
interface OpmlElement {
attributes: {
text:string
},
elements:OpmlElement[]
}
The desired object should resemble this:
interface ParsedTestCase {
title?: string;
suites?: string[];
}
Therefore, I need to define a parser that can handle this XML structure. Here is how I have set up the parser:
const elementParserTable= [
{
check: (e:OpmlElement) => getText(e).startsWith("tt:"),
takeValue: (e:OpmlElement) => getText(e),
cb: (v:string)=> {
testcase.title=v
}
} ,
{
check: (e:OpmlElement) => getText(e).startsWith("ts:"),
takeValue: (e:OpmlElement) =>getText(e).split(","),
cb: (v:string[])=> {
testcase.suites=v
}
},
]
My first issue arises when implementing the parser like above:
const elements:OpmlElement[]=[]
for (const e of elements) {
for (const elementParser of elementParserTable) {
if (elementParser.check(e)) {
elementParser.cb(elementParser.takeValue(e));
continue;
}
}
}
I receive the following error in TypeScript:
https://i.sstatic.net/AoXZd.png
Argument of type 'string | string[]' is not assignable to parameter of type 'string & string[]'. Type 'string' is not assignable to type 'string & string[]'. Type 'string' is not assignable to type 'string[]'.
How can I resolve this issue? Additionally, is there a way to enforce constraints on elementParser within elementParserTable to ensure type consistency between takeValue function and cb function parameters?