#Workaround undefined union property to make discriminated union
8 messages · Page 1 of 1 (latest)
please post snippets of code or links to the playground rather than images of code, so we can interact with it as text
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
}
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
...```
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