Search code examples
typescriptconstants

Define Typescript interface with using constant names as keys


I am trying to define an interface in TypeScript that uses key names from a constant object. However, I am encountering an issue where I am getting the following error:

Initializer type {[p: string]: string | number} is not assignable to variable type Test

Here is the code I am working with:

const KEYS: Record<string, string> = {
  KEY1: 'hello',
  KEY2: 'world'
}

interface Test {
  [KEYS.KEY1]: string;
  [KEYS.KEY2]: number;
}

const testData: Test = {
  [KEYS.KEY1]: 'javascript',
  [KEYS.KEY2]: 42,
}

Is there a way for me to use constants to define key names in an interface in TypeScript?


Solution

  • You can if you remove the Record<string, string> type annotation and add as const so that the keys become compile-time constants (because TypeScript works with compile-time information, not runtime information):

    const KEYS = {
        KEY1: "hello",
        KEY2: "world",
    } as const;
    

    Then the rest of your code works.

    Playground link