0

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

2 Answers 2

3

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

export type ValidatorSchema<T extends string> = Record<T, { validations: string[] }>;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks and I don't want all properties can I just wrap it in Partial? export type ValidatorSchema<T extends string> = Partial<Record<T, { validations: string[] }>>;
@AndréRicardo That is correct.
1

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[] }>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.