typescript - io-ts - Validera att en array innehåller ett av varje objekt med specifika egenskaper och värden
Jag tittade på https://github.com/gcanti/io-ts/ dokumentationen men kan inte hitta den validering jag behöver.
Jag har en array av objektliteraler, var och en med specifika egenskaper och värden.
Jag vill validera att comboItems inte är tomt och innehåller minst och högst 3 objekt OCH att det finns en itemType === 'Entree' OCH en itemType === 'Side' OCH en itemType === 'Beverage'
import * as t from "io-ts";
import { pipe } from 'fp-ts/function'
import { fold, isRight, isLeft } from 'fp-ts/Either'
enum ItemTypeEnum {'MEALS_GROUP'='MEALS_GROUP', 'ENTREES'='ENTREES', 'SIDES_GROUP'='SIDES_GROUP', 'BEVERAGES_GROUP'='BEVERAGES_GROUP'}
const Entree = t.type({
itemType: t.literal(ItemTypeEnum.ENTREES),
})
const Side = t.type({
itemType: t.literal(ItemTypeEnum.SIDES_GROUP),
})
type Entree = t.TypeOf<typeof Entree>
type Side = t.TypeOf<typeof Side>
export const Meal = t.type({
comboItems: t.readonlyArray(t.union([Entree, Side]))
})
Detta visas som en framgång (vilket är förväntat):
console.log(pipe(
Meal.decode({comboItems: [{itemType: ItemTypeEnum.ENTREES}, {itemType: ItemTypeEnum.SIDES_GROUP}]}),
fold(
// failure handler
(errors) => `error: ${JSON.stringify(errors)}`,
// success handler
(a) => `success: ${JSON.stringify(a)}`
)
)
)
Men detta visas också som en framgång, vilket det inte bör göra eftersom det saknas {{itemType: ItemTypeEnum.SIDES_GROUP}}
console.log(pipe(
Meal.decode({comboItems: [{itemType: ItemTypeEnum.ENTREES}]}),
fold(
// failure handler
(errors) => `error: ${JSON.stringify(errors)}`,
// success handler
(a) => `success: ${JSON.stringify(a)}`
)
)
)
Tack för all hjälp!