Reference/use value from the same object during parsing

This has probably been asked before but didn't have any luck searching for an answer. I have a type like this:
const configSchema = type({
cwd: type("string").default(process.cwd()),

"export-dir?": type("string").pipe((exportDir, ctx) => // default to cwd)
})
const configSchema = type({
cwd: type("string").default(process.cwd()),

"export-dir?": type("string").pipe((exportDir, ctx) => // default to cwd)
})
I would like to default export-dir to the value of cwd. It seems like I should be able to do this by accessing ctx.root but I was wondering if there's a type-safe/better way of doing this.
3 Replies
Genshii
GenshiiOP2d ago
Thinking about this more, I don't think this is possible? I assume the morphs are only evaluated if the export-dir key is defined. If export-dir is defined, then it will have a value, in which case I wouldn't use the default. Or in other words, it seems like I need a way to have ArkType always evaluate the morphs so I can handle the case when the key is missing (fallback to cwd) or use the given value. I guess I can just do this outside of the schema.
const configSchema = type({
cwd: type("string").default(process.cwd()),

"export-dir": type("string").default("")
})

// if exportDir is not provided (empty string), default to the given cwd
validated["export-dir"] = validated["export-dir"] || validated.cwd
const configSchema = type({
cwd: type("string").default(process.cwd()),

"export-dir": type("string").default("")
})

// if exportDir is not provided (empty string), default to the given cwd
validated["export-dir"] = validated["export-dir"] || validated.cwd
ssalbdivad
ssalbdivad2d ago
what about just moving the pipe up one level like this:
const configSchema = type({
cwd: type("string").default(process.cwd()),
"export-dir?": "string"
}).pipe(data => {
data["export-dir"] ??= data.cwd
})
const configSchema = type({
cwd: type("string").default(process.cwd()),
"export-dir?": "string"
}).pipe(data => {
data["export-dir"] ??= data.cwd
})
Genshii
GenshiiOP2d ago
oh, yeah don't why I didn't think of that thanks!

Did you find this page helpful?