function parseAndValidate(obj: unknown): ParsedObj | void {
try {
// do a lot of validations
return parsedObj
} catch {
throw new Error('obj is invalid')
}
}
const parsedObj = parseAndValidate(obj)
I have two questions:
- The LSP recognizes
parsedObjhas typeany. Why is that? - Why doesn't it recognize
parsedObjhas typeParsedObj, because otherwise an error will be thrown?
As the result, I have to force type it by using as ParsedObj.
That's because I didn't declare the
ParsedObjtype!In the playground, the type for
parsedObjreturns as expected (ParsedObj | void). If you remove the declaration it will returnany.As for the question 2, removing
voidwill help the LSP recognizesparsedObjto always have typeParsedObj. As Julio Di Egidio says, useneverfor self-documentation in that case, notvoid. TS is simply going to ignore it, asAnything | neverresolves to simplyAnything.