可选时未定义Typescript错误对象



我不是Typescript专业人士,但我已经了解了一点,我以为我已经完成了错误:"Object is possibly 'undefined'.ts(2532)"。但从今天下午开始,我就出现了这个错误,我不知道如何表明我的对象定义得很好。

我目前正在用Chevrotain编写一个解析器,并用这个解析器获得了一个树。现在我必须使用树来创建谓词对象。

我试着简化我的代码,告诉我是否有任何信息丢失来回答我。

我有以下接口:

export interface Predicates{
isError: boolean,
fullPredicates: string,
term?: Term,
termMatcher?: TermMatcher
}
export interface Term {
mainTerm: string,
isNegativeTerm: boolean
}

我有一个函数,通过浏览包含我感兴趣的数据的树来填充这个对象:

function extractTerm(node: CstNode): string {
nodeTerm = node.... //get string value which contain term name
return nodeTerm;
}
function extractFromTree(requestTree: CstNode[], fullText: string): Predicates {
const resultPredicates: Predicates = {
isError: false,
fullPredicates: extractFullPredicates(requestTree, fullText) //Here this function only return a string and it work well
};
let currentExpression: CstNode[] = [{
name: "",
children: {}
}];
//Here I place myself on the right branch of my tree to get the data by indicating the right path in "currentExpression"
//I removed this part to simplify but tell me if I should add it
//If current branch exist 
if (currentExpression[0].children[TERMINAL_LABELS.MAIN_TERM] !== undefined) {
//Here I have the error: "Object is possibly 'undefined'.ts(2532)"
resultPredicates.term.mainTerm = extractTerm(currentExpression[0]);
}
....
return resultPredicates as Predicates;
}

因此,在这种情况下,我尝试使用我所知道的两种方法来解决错误。

尝试一次

if(resultPredicates !== undefined && resultPredicates.term !== undefined) {
//Removes the error but at runtime the condition is considered as "undefined" and so we never enter it 
//even though I have data and my object should be built.
resultPredicates.term.mainTerm = extractTerm(currentExpression[0]);
}

正如评论中所说,这个方法删除了错误,但在运行时,条件被认为是undefined,因此当我有数据并且应该构建我的对象时,我们永远不会输入它。

尝试两次

if (currentExpression[0].children[TERMINAL_LABELS.MAIN_TERM] !== undefined) {
//Removes the "object is undefined" error but with this method each term of the expression has the following 
//error: "The left-hand side of an assignment expression may not be an optional property access.ts(2779)"
resultPredicates?.term?.mainTerm = extractTerm(currentExpression[0]);
}

正如评论中所说,此方法删除了object is undefined错误,但使用此方法,表达式的每个项都返回以下错误:The left-hand side of an assignment expression may not be an optional property access.ts(2779)

我还尝试将resultPredicates变量设置为Partial<Predicates>,但这也没有解决我的错误。

我一直在犯这个错误,如果有人看到我做错了什么,那会对我有很大帮助。如果你花时间帮助我,请提前感谢。

编译器正在帮助您。

您已定义。。。

const resultPredicates: Predicates = {
isError: false,
fullPredicates: extractFullPredicates(requestTree, fullText) //Here this function only return a string and it work well
};

然后你做

resultPredicates.term.mainTerm = extractTerm(currentExpression[0]);

此时,resultPredicates.term未定义。这里的解决方案是定义它。但这不会满足编译器的要求,因为它仍然可能是未定义的(假设类型将其作为可选)

您现在可以从resultsPredicates类型中删除Predicates,它将了解什么是设置的,什么是未设置的。如果你不想放弃类型,那么。。。

正如您所确定的,您不能使用可选的链式运算符,但现在可以断言该属性存在。

resultPredicates.term!.mainTerm = extractTerm(currentExpression[0]);

该变化是CCD_ 10到CCD_。

相关内容