Home > Net >  Interface keys from array in TypeScript
Interface keys from array in TypeScript

Time:05-14

Is there a way to enforce the keys of an interface to be used from an array of strings:

E.g. If we have the following array:

const myArray = ['key1', 'key2'];

I would like to create a new interface called MyInterface that would force all myArray entries to be object keys:

const myObj: MyInterface = {
  'key1': true,
  'key2': false,
}

CodePudding user response:

You can use the keyof operator for exactly this purpose.

interface MyInterface {
  key1: boolean;
  key2: boolean;
}

const myObj: MyInterface = {
  key1: true,
  key2: false,
}

const myArray: Array<keyof MyInterface> = ['key1', 'key2'];
// or ...
const myOtherArray: Array<keyof typeof myObj> = ['key1', 'key2'];

You could also go backwards like so

const myArray = ['key1', 'key2'] as const;

type MyType = Record<typeof myArray[number], boolean>;

const myObj: MyType = {
  key1: true,
  key2: false,
}
  • Related