#How to avoid lying to typescript inside type guards?

12 messages · Page 1 of 1 (latest)

lapis mulch
#

Let's say I have a union type as such, and want to implement a type guard, I can lie within the typeguard:

type A = {
  on: false,
  powered: false,
}
type B = {
  on: true,
  powered: true
}
type C = {
  on: false,
  powered: true
}

type AllStates = A | B | C

function isA(state: AllStates): state is A {
  return state.on === false // but actually this could also be C
}

Is there a way to ensure that I can't accidentally do this?

#

If I wasn't using a type guard, my type could be narrowed appropriately:

const state = {} as unknown as AllStates
if (!state.on) {
  // here state is inferred as A | C
}
#

Is this simply a situation where type guards aren't the tool I want?

steep carbon
#

can't

#

the entire point of typeguards is because typescript isn't powerful enough to figure this out itself

lapis mulch
#

yeah figured so

#

I mean I guess I could go through those if statements inside the typeguard to ensure for the branches I check, I'm not lying, but still isn't perfect

steep carbon
#

i mean

#

another alternative is to avoid type guards altogether

#
function tryGetA(state: AllStates): A | undefined
lapis mulch
#

Yeah I think I will avoid them here

#

ty