Search code examples
typescriptzod

How to represent a partial record in zod?


I need to represent a Partial<Record<SomeEnum, boolean>> with zod.

In TypeScript, we can do this easily:

type SomeEnum = 'one' | 'two'
type MyRecord = Record<SomeNum, boolean>
type MyRecordPartial = Partial<MyRecord>

With zod, we can represent the enum and record, but not the partial record?

const SomeEnum = z.enum(['one', 'two'])
const MyRecord = z.record(SomeEnum, z.boolean());
const MyRecordPartial = MyRecord.partial() // This is not a method for Records.

What's the idoimatic way of doing this?


Solution

  • zod records are partial by default:

    import { z } from 'zod'
    
    const SomeEnum = z.enum(['one', 'two'])
    
    const MyRecord = z.record(SomeEnum, z.boolean());
    
    type MyRecordType = z.infer<typeof MyRecord>
    // {
    //    one?: boolean | undefined;
    //    two?: boolean | undefined;
    // }
    
    const testA: MyRecordType = { one: true } // fine
    

    See playground

    You actually have to do extra work to make all the keys required. See a related question I asked a while back about how to do that.