Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
harlos0517 opened this issue Oct 18, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@harlos0517
Copy link

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 harlos0517 changed the title Feature Request: support computed property (such as enum value) as object key Feature Request: support computed property (such as enum value) as property key Oct 18, 2023
@harlos0517
Copy link
Author

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

@tvillaren tvillaren added the enhancement New feature or request label Mar 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants