gvergnaud / ts-pattern

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.
MIT License
12.5k stars 135 forks source link

How do I return a string | null from a match #198

Closed st-clair-clarke closed 1 year ago

st-clair-clarke commented 1 year ago

I have the following:


export type TValidationMessage = {
      id: string
      maxLength?: number
      minLength?: number
      subject?: string
}

export const messages = ({id, subject='', minLength, maxLength}: TValidationMessage): string | null =>
   match( id )
      .with('maxStringLength', () =>  maxStringLengthMessage( { id, subject, maxLength })
     .with( 'minStringLength', () => minStringLengthMessage( { id, subject, minLength }) 
     .otherwise(() => `No validation message found with ID ${id}!`)

If a match is successful, a string is returned. If it is not successful I would like null to be returned. I could return null in the .otherwise(), but then I would loose the specific specific message, which I don't want either.

zoontek commented 1 year ago
export const messages = ({id, subject='', minLength, maxLength}: TValidationMessage) =>
   match( id )
     .returnType<string | null>()
     .with('maxStringLength', () =>  maxStringLengthMessage( { id, subject, maxLength })
     .with( 'minStringLength', () => minStringLengthMessage( { id, subject, minLength }) 
     .otherwise(() => null)
st-clair-clarke commented 1 year ago

Thanks