vendredi 24 juillet 2020

how to handle `Type | boolean` return values in typescript and error checking / tests

I have a function that can return a found object, or fail. What's the best value to return in the failure case? {}|null|undefined|false

The problem is my test rely on this object, but I get typescript warnings as false could also be returned

    const actualResult: ActionResult | boolean = await findAndRunAction(evt)
    if (actualResult) {
      expect(actualResult.klass).toBe('room')

where

function findAndRunAction(): ActionResult | false { 
// if found
return obj: ActionResult
// else
return false
 }

typescript is smart enough to know the value must be truthy but that should be when I am returning an instance of the full object, not just true.

I could throw an error, or the other way would be to always return the same object type but just add a ok: true|false field into the object. That seems a bit excessive, but I guess it does mean I always only have one return type...

Suggestions for good patterns to use with this in TS please!

ts problems

failing test

The compiler fails, but the actual test is passing.

Update: I did something like this:

// define all the other fields as optional

interface ActionResult {
  ok: boolean
  doc?: ActionData
  events?: string[]
  klass?: string
}

// so I can just return an empty obj in fail case

    return {
      ok: false
    }

I don't like this so much as it gives less rigidity on the actual type with all these options.

Aucun commentaire:

Enregistrer un commentaire