ts-to-zod icon indicating copy to clipboard operation
ts-to-zod copied to clipboard

Feature Request: support computed property (such as enum value) as property key

Open harlos0517 opened this issue 1 year ago • 1 comments

Feature description

If the key of a property is not a literal, original behavior is it will be ignored.

It would be nice to support computed property key (such as constants and enum values)

I did found a quick way to work by modifying the source code:

// src/core/generateZodSchema.ts:190
    if (
      !ts.isPropertySignature(member) ||
      !member.type ||
      !(
        ts.isIdentifier(member.name) ||
        ts.isStringLiteral(member.name) ||
-       ts.isNumericLiteral(member.name)
+       ts.isNumericLiteral(member.name) ||
+       ts.isComputedPropertyName(member.name)
      )
    ) {
      return;
    }

But there might be edge cases I haven't thought of.

Input

export enum COL {
  MODEL = 'T0000'
}

export type Car = {
  [COL.MODEL]: string
}

Original Output

// Generated by ts-to-zod
import { z } from 'zod'
import { COL } from 'src/col'

export const colSchema = z.nativeEnum(COL)

export const carSchema = z.object({})

Desired Output

// Generated by ts-to-zod
import { z } from 'zod'
import { COL } from 'src/col'

export const colSchema = z.nativeEnum(COL)

export const carSchema = z.object({
  [COL.MODEL]: z.string(),
})

harlos0517 avatar Oct 18 '23 01:10 harlos0517

Ah I think it should check if computed property evaluates into string constant

harlos0517 avatar Oct 18 '23 02:10 harlos0517