#Workaround undefined union property to make discriminated union

8 messages · Page 1 of 1 (latest)

obtuse stream
#

hello, I'm new to typescript - is there a way I can workaround the shared "undefined" here to use shared as discriminant property and narrow the type?

ember pike
#

please post snippets of code or links to the playground rather than images of code, so we can interact with it as text

obtuse stream
#
type X = {
   shared: "X" | undefined
   x: number
}

type Y = {
   shared: "Y" | undefined
   x: number
   y: boolean
}

type Z = {
   shared: "Z" | undefined
}

type XYZ = X | Y | Z

const getXofData = (data: XYZ) => {
   if (data.shared == "Z") {
      return "nuh uh"
   }
   return data.x
}
mint patrolBOT
#
that_guy977#0

Preview:```ts
type X = {
shared: "X" | undefined
x: number
}

type Z = {
shared: "Z" | undefined
}

type XYZ = X | Z

const z: Z = {shared: undefined}

const getXofData = (data: XYZ) => {
if (data.shared === "Z") {
return "nuh uh"
}
// data is z, no x propert
...```

ember pike
#

this is kinda a discriminated union already. but the undefined means it's not exclusive

#

you could pass a Z with a shared: undefined, and getXofData wouldn't be able to tell if it was a X or a Z

#

so there's nothing to work around here, this is just a plain issue that ts is warning you about

#

if you want to check if x exists, just check for that directly; 'x' in data