Z
Zod6mo ago
ménard

ménard - I'm thinking of something like:typesc...

Hi, is there a way without going out of band to make one field always have the same value as another even when it's not part of the input object? I'm thinking of something like:
const vpm = z.object({
leader: z.number(),
follower: z.getsItsValueFrom('leader')
// ...
});

vpm.safeParse({leader: 123}) // { data: { leader: 123, follower: 123 } }
const vpm = z.object({
leader: z.number(),
follower: z.getsItsValueFrom('leader')
// ...
});

vpm.safeParse({leader: 123}) // { data: { leader: 123, follower: 123 } }
4 Replies
Svish
Svish6mo ago
If it's always the same value, then it doesn't really make sense to me to even have it in the input. If it's necessary in the output, I would just add it with a transform on the object.
.transform(obj => ({
...obj,
follower: o.leader,
}))
.transform(obj => ({
...obj,
follower: o.leader,
}))
ménard
ménardOP6mo ago
It's not supposed to be in the input. 🙂 I'll try using .transform like that.
const vpm = z
.object({
leader: z.number(),
})
.transform((obj) => ({
...obj,
follower: obj.leader,
}));
it('leader and follower 001', () => {
const ret = vpm.safeParse({ leader: 123 });

expect(ret.success).toBe(true);
expect(ret.data?.leader).toBe(123);
expect(ret.data?.follower).toBe(123);
});
const vpm = z
.object({
leader: z.number(),
})
.transform((obj) => ({
...obj,
follower: obj.leader,
}));
it('leader and follower 001', () => {
const ret = vpm.safeParse({ leader: 123 });

expect(ret.success).toBe(true);
expect(ret.data?.leader).toBe(123);
expect(ret.data?.follower).toBe(123);
});
it does exactly what I hoped it would Thanks, @Svish
Svish
Svish6mo ago
Cool. Not sure I'd bother writing a unit test for that though 😛
ménard
ménardOP6mo ago
Haha I write tests to check my understanding of programming language and library features all the time
Want results from more Discord servers?
Add your server