Search code examples
typescripttypestypeerrorzod

change array.map() output a type that zod enum can take


I have the following code

export const taxTypeArray = [
  {value: 'INCLUSIVE' as const, label: '外税'},
  {value: 'EXCLUSIVE' as const, label: '内税'},
]

const test = taxTypeArray.map((item) => item.value)

export const taxType = z.enum(test)

and it gives the following error:

Argument of type '("INCLUSIVE" | "EXCLUSIVE")[]' is not assignable to parameter of type 'readonly [string, ...string[]]'.

the reason is that the type of test needs to be

type ["INCLUSIVE", "EXCLUSIVE"]

but array.map outputs the following type

type ("INCLUSIVE" | "EXCLUSIVE")[]

Is there a way I can change it so that testis of a type that z.enum can take?
I'd like to keep the types intact so I'd rather not use the following:

const test = taxTypeArray.map((item) => item.value) as [string, ...string[]]

Solution

  • I would not use .map to calculate the array, this contains JS logic. Use z.nativeEnum() and declare the TaxType TS enum. Keep code simple and with as little logic as possible.

    import { z } from 'zod';t
    
    enum TaxType {
        INCLUSIVE = 'INCLUSIVE',
        EXCLUSIVE = 'EXCLUSIVE'
    }
    
    export const taxTypeArray = [
        { value: TaxType.INCLUSIVE, label: '外税' },
        { value: TaxType.EXCLUSIVE, label: '内税' },
    ]
    
    export const taxType = z.nativeEnum(TaxType);
    
    
    console.log(taxType.parse(TaxType.EXCLUSIVE))