When using XMLValidator, the return value of .validate function can be either true or ValidationError, but this may not be entirely accurate (please refer to my update). The ValidationError object includes an err property.
validate( xmlData: string, options?: validationOptionsOptional): true | ValidationError
In JavaScript, since boolean primitives are wrapped in objects, we can simply check for the existence of the err property to determine if the validation was successful.
const result = XMLValidator.validate(message)
if (result.err) { // How do I make it work in ts?
console.log(`invalid XML')
} else {
console.log(`valid XML`)
}
However, TypeScript does not allow this and will throw an error 'Property 'err' does not exist on type 'true''.
I find checking the return type first to be verbose and since there is no explicit return value type definition (refer to my update), I'm looking for a more concise way to write this code in TypeScript.
--- update ---
I examined the validator.js code
const isValid = validateAttributeString(attrStr, options);
if (isValid !== true) {
return getErrorObject(...);
}
...
function getErrorObject(code, message, lineNumber) {
return {
err: {
code: code,
msg: message,
line: lineNumber.line || lineNumber,
col: lineNumber.col,
},
};
}
It appears that the only solution here might be to use `if (typeof result == "boolean")`, though I am hopeful for a more general approach to address this issue.