#Setting Optional Nested Item

15 messages · Page 1 of 1 (latest)

eternal forum
#

If I have a nested item whose type is optional, how do I set the value in a type-safe way.

For example:

type Bar = {
  baz: string;
}

type Foo = {
  bar: Bar
}

type PartialFoo = Partial<Foo>;

const setBaz = (p: PartialFoo, newBaz: string): PartialFoo => {
  p.bar.baz = newBaz;
}

In this case, I have a type error because bar might not exist, so it's looking for a ?.. If Bar doesn't exist, I want it to exist. Is there a concise way to do this other than creating a bunch of logic testing each tier if its undefined and successively building the tree?

mighty quartzBOT
#

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

robozoom#0

Preview:```ts
type Bar = {
baz: string
}

type Foo = {
bar: Bar
}

type PartialFoo = Partial<Foo>

const setBaz = (
p: PartialFoo,
newBaz: string
): PartialFoo => {
p.bar.baz = newBaz
}```

fallow widget
#

Something like p.bar ??= { baz: newBaz } should work in a scenario like this, the more complicated it gets the more i would advise adding a check like typeof x === "undefined" or something like that

turbid briar
#

Alternatively:

p.bar = { ...p.bar, baz: newBaz }

This can be extended to arbitrary depth, just need to spread each layer all the way to the last.

eternal forum
#

I'm looking at a case with multiple tiers

#

I tihnk the second case is probably more applicable, but I was hoping that there was a utility function or something that made this a bit more clean

#

For context, I'm building utility functions to change specific properties within a chart.js configuration object... which is highly layered and variable depending on how much you want to customize any given graph

turbid briar
#

I mean you can write one, it's only a few lines.

#

Although to get nice autocomplete would be a bit annoying.

eternal forum
#

yeah

#

Ok, at least I know I'm not missing something fundamental here

turbid briar
#

You can write a recursive type for it or bring in a library, but honestly it feels way overkill.

turbid briar
#

It's probably easier to just have an initial options object with all the potential modified properties set to default, so you can modify directly without needing to care about missing nested objects all the way down.