Typescript 如何声明ts中函数之间的依赖关系?
对不起,标题太混乱了,我不知道该如何清楚地解释我的问题。 目前,我正在尝试实现一种可以从xml解析对象的方法。 xml(使用xml js转换为js)如下所示Typescript 如何声明ts中函数之间的依赖关系?,typescript,Typescript,对不起,标题太混乱了,我不知道该如何清楚地解释我的问题。 目前,我正在尝试实现一种可以从xml解析对象的方法。 xml(使用xml js转换为js)如下所示 interface OpmlElement { attributes: { text:string }, elements:OpmlElement[] } interface ParsedTestCase { title?: string; suites?: string[]; } 目标对象如下所示
interface OpmlElement {
attributes: {
text:string
},
elements:OpmlElement[]
}
interface ParsedTestCase {
title?: string;
suites?: string[];
}
目标对象如下所示
interface OpmlElement {
attributes: {
text:string
},
elements:OpmlElement[]
}
interface ParsedTestCase {
title?: string;
suites?: string[];
}
所以,我想声明某种解析器来解析这个xml。idefine是一种解析器
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
}
},
]
第一个问题是我什么时候使用上面提到的方法
const elements:OpmlElement[]=[]
for (const e of elements) {
for (const elementParser of elementParserTable) {
if (elementParser.check(e)) {
elementParser.cb(elementParser.takeValue(e));
continue;
}
}
}
ts抱怨说我怎样才能避免这种情况?
第二个问题是:是否有某种方法在elementParserTable中约束elementParser,以确保takeValue函数的返回类型是cb函数的参数类型?我不确定不强制转换(
elementParser.cb(elementParser.takeValue(e)作为任何类型)就可以避免错误
要回答第二个问题,可以确保take value的返回类型是具有通用接口的cb参数。例如:
interface ElementParser<T> {
check: (e: OpmlElement) => boolean,
takeValue: (e: OpmlElement) => T,
cb: (v: T) => void
}
const elementParserTable: Array<ElementParser<string> | ElementParser<string[]>> = [...]
接口元素分析器{
检查:(e:OpmlElement)=>布尔值,
takeValue:(e:OpmlElement)=>T,
cb:(v:T)=>void
}
const elementParserTable:Array=[…]
当然,对于typescript没有存在类型这一事实,所有这些都只是一个蹩脚的解决办法。我建议在一种方法中组合takeValue
和cb
const elementParserTable= [
{
check: (e: OpmlElement) => getText(e).startsWith("tt:"),
cb: (e: OpmlElement) => {
testcase.title = getText(e);
},
},
{
check: (e: OpmlElement) => getText(e).startsWith("ts:"),
cb: (e: OpmlElement)=> {
testcase.suites = getText(e).split(",");
},
},
];
使用方法:
const elements: OpmlElement[] = [];
for (const e of elements) {
for (const elementParser of elementParserTable) {
if (elementParser.check(e)) {
elementParser.cb(e);
continue;
}
}
}
我认为您可以尝试在一种方法中组合检查
,获取值
和cb
。但我不确定这是否是您的情况。您可以执行另一个函数,让typescript知道它是否是字符串
isTitle(titleOrSuite:string|string[]) titleOrSuite is string{
return typeof titleOrSuite === "string";
}
数组中实际上只有两个元素解析器,还是这只是一个例子?作为一个例子,它可以是任意数量的元素解析器,每个解析器的类型可能不同。正如任何..是某种黑客行为,我不太明白为什么会发生此错误。这是由于类型推断对函数参数的影响。我记得一些详细的explanation by jcalz,让我为您搜索。@hackape这个问题的解决方案称为存在类型,但ts没有它。