假设我有这个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();
但是,当推断类型并使用该类型创建对象时,它似乎并不建议要定义的字段。
1条答案
按热度按时间zlwx9yxi1#