#foo:undefined vs not specified in discriminated union

4 messages · Page 1 of 1 (latest)

unique geode
#

I am a bit confused about missing properties.

I wrote a function notwork,which can accept either a foo or a bar property. But destructuring does not handle it nicely. I have to specify the missing props explicity (see works), but this seems weird.

Can I circumvent this and simplify the typing?

https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAggmB3BAnA1gZwAoAHbBY-ALmQG8QEFqIwBbAIwFNsBfZAH1psAhtiatOPAJS1gyZFCT4YteggA0yYT2QBeZKXL4A3MgD0p5AE1kAVWQghcADYB+WfMUInHAHROEAOaEAAaq1AAkdAzcGloRNFrcwZLA3MCgkLCIKFh4RAYU1FGMqOJcsSLUkAAmHCBwEBzVvALFVRC19Y3VFaKl7Fzc0jTuChBKKgy9vHoFxulyY-hevv5BoQzxqjGalciRicmpQA

raw starBOT
#

@unique geode Here's a shortened URL of your playground link! You can remove the full link from your message.

pihentagy#0

Preview:```ts
function notworks(
props: {foo: number} | {bar: number}
) {
const {foo, bar} = props // Y U fail?
console.log(foo: ${foo}, bar: ${bar})
}

function works(
props:
| {foo: number; bar: undefined}
| {foo: undefined; bar: number}
) {
const {foo, bar} = props
...```

iron ibex
#

The main problem I believe is that you are accessing both foo and bar in both, but in notworks one of the properties will not exist. To remedy this, you can specify if ("foo" in props) { /* do stuff with foo */ } to guard which type you're with.

Discriminated unions can also help by adding a "tag" to the objects: { type: 'foo'; foo: number; } | { type: 'bar'; bar: number; } This would allow you to inspect the shared type property of both as your guard.

unique geode
#

Ok, but in fact it is a react component. You can either specify foo or bar. So I would avoid discriminator if possible.