Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript generic record with given keys

I’m trying to validate in TypeScript an object contains the given keys (from SingleShopColumns or MultishopColumns) and has a validations that is an array of strings.

Using Record and generics but any simple way of representing this shape in a generic way would be a valid answer.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Getting an error
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>'.

>Solution :

T is already a key. Remove the keyof and add a constraint:

export type ValidatorSchema<T extends string> = Record<T, { validations: string[] }>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading