#Omit key from object type nested in array(s)

12 messages · Page 1 of 1 (latest)

pearl ruin
#

if we assume a type Crumb defined as

type Crumb = { id: string; title: string; href?: string };

and we have the type Crumbs (with an s at the end) defined as

type Crumbs = (Crumb | Crumb[])[];

how could i then create a 3rd type that's practically a duplicate of Crumbs but with the id key omitted?

My current solution is as such:

type SimpleCrumbs = (Omit<Crumb, "id"> | Omit<Crumb, "id">[])[];

and it works how i want it to, but i'd prefer not having code duplication. Essentially i want to "transform" Crumbs into a nearly identical type, but with the id key omitted.

hollow yarrow
#

you could just do like,

type SimpleCrumb = Omit<Crumb, "id">
type SimpleCrumbs = (SimpleCrumb | SimpleCrumb[])[];
cerulean path
#

@pearl ruin In theory, if this is a common pattern you could make a helper for it:

type OmitDeep<T, K extends string> = T extends Array<infer U> ? Array<OmitDeep<U, K>> : Omit<T, K>
type SimpleCrumbs = OmitDeep<Crumbs, "id">
#

But yeah, I'd probably not. In reality, would probably do something like this:

type OneOrMore<T> = Array<T | T[]>
type SimpleCrumb = { title: string, href?: string }
type Crumb = SimpleCrumb & { id: string }
pearl ruin
hollow yarrow
pearl ruin
hollow yarrow
#

i'm not redefining Crumb there, i'm doing this lol

"transform" Crumbs into a nearly identical type, but with the id key omitted.

#

ah wait that says Crumbs, mb

pearl ruin
hollow yarrow
pearl ruin
#

anyway, i'm probably gonna go with the second implementation suggested by @cerulean path, as it slots in pretty well with what i had in mind

type OneOrMore<T> = Array<T | T[]>
type SimpleCrumb = { title: string, href?: string }
type Crumb = SimpleCrumb & { id: string }

i'll go test it out if it also works how i'd expect and then close this issue if it does