'Interface keys from array in TypeScript
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,
}
Solution 1:[1]
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,
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | emeraldsanto |