Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Created January 23, 2024 02:53
Show Gist options
  • Save codeBelt/fc9baf4f6b07e865ecb098b9dbac673c to your computer and use it in GitHub Desktop.
Save codeBelt/fc9baf4f6b07e865ecb098b9dbac673c to your computer and use it in GitHub Desktop.
TypeScript Object with Dynamic Keys

https://www.basedash.com/blog/typescript-object-with-dynamic-keys

Constrained Dynamic Keys At times, you'd want to constrain the dynamic keys to a specific set of values, perhaps based on another array or tuple.

const validKeys = ['a', 'b', 'c'] as const;

type ValidKeysType = typeof validKeys[number];

type ConstrainedDictionary = Record<ValidKeysType, string>;

const obj: ConstrainedDictionary = {
  a: "valueA",
  b: "valueB",
  c: "valueC",
};

https://stackoverflow.com/questions/53662208/types-from-both-keys-and-values-of-object-in-typescript

const KeyToVal = {
    MyKey1: 'myValue1',
    MyKey2: 'myValue2',
} as const;

type Keys = keyof typeof KeyToVal;
type Values = typeof KeyToVal[Keys]; //  "myValue1" | "myValue2"
const keyToValArray = [
  { value: 'myValue1', label: 'myLabel1' },
  { value: 'myValue2', label: 'myLabel2' }
] as const;
type Keys = typeof keyToValArray[number]['value']; // 'myValue1' | 'myValue2'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment