Home > Net >  TypeScript generic record with given keys
TypeScript generic record with given keys

Time:10-15

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

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>'.

CodePudding user response:

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

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

CodePudding user response:

Your T is aleady an union of keys, thus just

export type ValidatorSchema<T extends string|number|symbol> = 
    Record<T, { validations: string[] }>;

rather than

export type ValidatorSchema<T> = 
    Record<keyof T, { validations: string[] }>;
  • Related