#Why do I have to explicitly type `undefined` in an object?

14 messages · Page 1 of 1 (latest)

sharp plover
#

Given this Code:

type GameDisplayProps =
  | {
      as: "link";
      id: string;
    }
  | {
      as: "div";
      id: undefined;
    };

const test = ({as, id}: GameDisplayProps) => `help ${id}`

test({
  as: 'div', 
  id: undefined // why??? 
});

As you can see, I have to explicitly pass id as undefined in this object, but why? The default behaviour of JS would be to set it to undefined anyways, so why do I have to explicitly type it? Am I doing something wrong or is there a better way to achieve this? (when I don't pass id in ```ts
{ as: 'div', id: undefined}

keen cloak
#

You’d want to define the type as so instead

type GameDisplayProps = {
  as: 'link' | 'div'
  id?: string
}
sharp plover
#

Hi, thanks alot for your response! I guess there isn't a way to explicitly type when id is defined and when its undefined then?

keen cloak
#

That's how you do it

#

...and all these will be valid

const a: GameDisplayProps = {
  as: 'div',
  id: undefined
}
const b: GameDisplayProps = {
  as: 'link',
}
const c: GameDisplayProps = {
  as: 'div',
  id: 'some value'
}
sharp plover
#

Yeah, that's probably the simpler answer... thx alot!

#

!resolved

tropic portal
#

oh, they left.

#

rip.

#

doing id?: undefined wouldve been much simpler and maintained link needing a string

keen cloak
tropic portal