Home > Enterprise >  How to create a typescript Record that allows keys that reference another constant variable of type
How to create a typescript Record that allows keys that reference another constant variable of type

Time:11-30

I have one const like this

const KEYS: Record<string, string> = {
    KEY1: 'k1_mightBeAnything',
    KEY2: 'k2_hmm',
} as const;

Then I want to create a type like

type ValidationErrors = Partial<Record<'k1_mightBeAnything' | 'k2_hmm', string | null>>;

So I want to automate this part 'k1_mightBeAnything' | 'k2_hmm' to automatically infer those values from the constant value named KEYS

How to do that ?

I did my homework, researched a lot and tried

type ValidationErrors = Record<typeof KEYS[keyof typeof KEYS], string>)

But I do not see it working. The editor is not suggeting anything out of it, or preventing to set errors for keys that don't exist like. So not working shortly. One example below

const errors = {'banana': 'whatever'};

should be flagged with error, only these keys need to be allowed 'k1_mightBeAnything' | 'k2_hmm' but with above type I tried doesn't do so

Thanks

CodePudding user response:

Your example seems to be working fine in the enter image description here

const KEYS: Record<string, string> = {
    KEY1: 'k1_mightBeAnything',
    KEY2: 'k2_hmm',
} as const;

type ValidationErrors = Partial<Record<'k1_mightBeAnything' | 'k2_hmm', string | null>>;

const validObject: ValidationErrors = {'k1_mightBeAnything': 'whatever'};
const alsoValidObject: ValidationErrors = {'k2_hmm': 'whatever'};
const invalidObject: ValidationErrors = {'banana': 'whatever'};

Click here to open above code in TS Playground

CodePudding user response:

You can use an interface or enum:

interface KEYS {
  'k1_mightBeAnything': string;
  'k2_hmm': string;
}

type ValidationErrors = Record<keyof KEYS, string | null>;

--or--

enum KEYS {
    'k1_mightBeAnything' = 'k1_mightBeAnything',
    'k2_hmm' = 'k2_hmm',
}

type ValidationErrors = Record<keyof typeof KEYS, string | null>;
  • Related