typescript 将对象键转换为zod模式

n53p2ov0  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(133)

假设我有这个json对象:

const amenities = { "wifi": "Wifi", "tv": "Tv", "steamIron": "Steam iron", "kitchenette": "Kitchenette", "fridge": "Fridge", "airConditioner": "Air conditioner", "fan": "Fan", "gym": "Gym", "pool": "Pool", "parking": "Parking", "lounge": "Lounge", "laundry": "Laundry", "stove": "Stove", "balcony": "Balcony", "microwave": "Microwave", "oven": "Oven", "desk": "Desk", "towels": "Towels", "bedSheets": "Bed sheets", "studyRoom": "Study room", "chair": "Chair", "table": "Table", "elevator": "Elevator", "generator": "Generator", "security": "Security", "cafe": "Cafe", "restaurant": "Restaurant", "housekeeping": "Housekeeping" }

我想创建一个zod模式,它的作用和下面一样:

interface Amenities extends Record<keyof typeof amenities, boolean> {}

结果会是这样的:

const a: amenities = { wifi: false, tv: true, ... }

我怎样才能做到这一点,而不重新定义键?
我试过这个:

export const Amenities = z.record(z.boolean()).refine((val) => {
    const keys = Object.keys(amenities);
    for (const key of keys) {
        if (!(key in val)) {
            return false;
        }
    }
    return true;
}, {
    message: 'Amenities should have all keys defined',
}).nonstrict();

但是,当推断类型并使用该类型创建对象时,它似乎并不建议要定义的字段。

zlwx9yxi

zlwx9yxi1#

const Amenities = z.record(
  z.custom<keyof typeof amenities>((data) => {
    return typeof data === "string" && data in amenities;
  }),
  z.boolean()
);

相关问题