I need to validate in TypeScript whether an object contains the specified keys (from SingleShopColumns
or MultishopColumns
) and has a validations
property that is an array of strings.
I am using Record and generics, but any simple method of representing this structure in a generic way would suffice.
export type SingleShopColumns =
| 'SKU'
| 'Priority';
export type MultishopColumns =
| 'Redundant Date'
| 'Priority';
export type ValidatorSchema<T> = Record<keyof T, { validations: string[] }>;
export const SINGLE_SHOP_SCHEMA: ValidatorSchema<SingleShopColumns> = {
'SKU': {
validations: ['validateString']
},
'Priority': {
validations: ['validateString']
},
'Does_not_exist_should be error': {
validations: ['validateString']
}
};
export const MULTISHOP_SCHEMA: ValidatorSchema<MultishopColumns> = {
'Redundant Date': {
validations: ['validateString']
},
'Priority': {
validations: ['validateString']
}
};
TypeScript playground with this code
Encountering an issue
Type '{ SKU: { validations: string[]; }; Priority: { validations: string[]; }; 'Does_not_exist_should be error': { validations: string[]; }; }' is not assignable to type 'ValidatorSchema<SingleShopColumns>'. Object literal may only specify known properties, and ''SKU'' does not exist in type 'ValidatorSchema<SingleShopColumns>'.