Kristi Jorgji
Kristi Jorgji

Reputation: 1721

How to create a typescript Record that allows keys that reference another constant variable of type record?

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

Upvotes: 0

Views: 3049

Answers (2)

Martin Devillers
Martin Devillers

Reputation: 17992

Your example seems to be working fine in the TypeScript Playground. I would check out the configuration of your IDE.

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

Upvotes: 2

Lance
Lance

Reputation: 741

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>;

Upvotes: 0

Related Questions