An object is validated via a try-catch block. Why does the LSP recognize its type incorrectly?

41 Views Asked by At
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 parsedObj has type any. Why is that?
  • Why doesn't it recognize parsedObj has type ParsedObj, because otherwise an error will be thrown?

As the result, I have to force type it by using as ParsedObj.

1

There are 1 best solutions below

0
Ooker On

That's because I didn't declare the ParsedObj type!

In the playground, the type for parsedObj returns as expected (ParsedObj | void). If you remove the declaration it will return any.

As for the question 2, removing void will help the LSP recognizes parsedObj to always have type ParsedObj. As Julio Di Egidio says, use never for self-documentation in that case, not void. TS is simply going to ignore it, as Anything | never resolves to simply Anything.