ts-to-zod
ts-to-zod copied to clipboard
Feature Request: support computed property (such as enum value) as property key
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(),
})
Ah I think it should check if computed property evaluates into string constant