#How to remap const asserted object to tuple in a safe manner

1 messages · Page 1 of 1 (latest)

crimson mortarBOT
#
tickleme_pink#0

Preview:```ts
const env = {
dev: {
name: "dev",
data: "data",
},
prod: {
name: "prod",
data: "data",
},
} as const

const envNames = Object.values(env).map(x => x.name)
// ^^^^^ ("dev"|"prod")[]

// How to keep const assertion and turn this into a tuple ["dev", "prod"] without any unsafe constructs?```

hasty creek
#

you can't. objects are conceptually unordered, and ts' object types aren't ordered either

#

Object.values() itself is kinda unsafe

ionic jacinth
#

I suppose then I need to do the reverse?

#

From array to object

hasty creek
#

that would work yeah

#

seems like fromEntries isn't very specific though

ionic jacinth
#

Actually even from a const array I can't get a tuple of the names.

hasty creek
#

yeah you'd still have to assert, map doesn't consider tuples

#

do you really need a tuple though?

ionic jacinth
#

I believe so, I want to use it in a io-ts decoder D.literal

hasty creek
#

well im not familiar with that so i can't comment on that

ionic jacinth
#

D.literal(...envNames); ■ A spread argument must either have a tuple type or be passed to a rest parameter.

hasty creek
#

i don't think passing "dev", "prod" is right for that

#

like, as the error says, you would probably want a rest parameter for that, which isn't there

#

otherwise it would have to expect exactly 2 strings for.. 2 environments?

ionic jacinth
#
D.literal(...envNames);```
hasty creek
#

so a value of "dev" named "prod"?

#

yeah that doesn't sound right

ionic jacinth
#

so a value of "dev" named "prod"?
What do you mean?

hasty creek
#

that's what the docs say for literal

#

unless it isn't that, but i didn't find anything else for literal in that page

#

oh wait i was on the wrong page

#

well, Decoder.literal takes a rest parameter.

ionic jacinth
hasty creek
#

yeah, you might not be using the right thing?

ionic jacinth
#

Not sure.

hasty creek
#

the rest parameter is being spread within the signature..

crimson mortarBOT
#
that_guy977#0

Preview:```ts
import D from "io-ts/lib/Decoder"

declare const x: string[]

D.literal("", ...x)

D.literal```

hasty creek
#

this is weird

ionic jacinth
#

yea idk how to use that "rest" param tbh.

hasty creek
#

seems like it's breaking because of the [Literal, ...Literal] type

#

oh, wait, im dumb.

#

D.literal says that it requires at least 1 element

#

but a string[] doesn't fulfill that requirement

ionic jacinth
#

I suppose I can do t.keyof and work with an object but enforce name === key

hasty creek