Skip to content

Allow data and error to be accessed on SafeParseReturnType even when they may not be present #3325

@schicks

Description

@schicks

When using zod in react applications, the error property is often unused. Instead, the primary focus is on either getting back parsed data or undefined (which can then be overwritten with some default value). Currently this involves a pointless intermediate variable.

import {MyThingParser} from '../parsers'

const useMyThing = () => {
	const myThingResult = MyThingParser.safeParse(localStorage.get('myThingKey'))
	const myThing = myThingResult.success ? myThingResult.data : defaultMyThing
	// ... further transformations, defaulting, etc.
}

These sorts of patterns also come up frequently in tests, where it is usually solved with very broad casting.

test('myThing is parsed correctly', () => {
  const myThingResult = MyThingParser.safeParse(testData)
  expect((myThingResult as any).data).toEqual(testData)
})

Both of these would be unneccessary if we made a slight change to the safe parse output type, while keeping the discriminated union structure.

type SafeParseSuccessOutput<Output> = { 
    success: true; 
    data: output; 
    error? : never
}

type SafeParseError<Input> = { 
    success: false; 
    error: ZodError<Input>; 
    data? : never
}

This was initially discussed in #3266 , but that was closed because the original suggestion in that thread involved removing the discriminated union structure. There is a PR for this work already (#3295 ).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions