Get Keys of a Typescript Interface as Array of Strings

How to get keys type as array from interface?

See the question that Jared mentioned.

If control over the order of the keys matters in the array, it is better to define the array and derive the shape of your interface from the array:

TS Playground

const exampleKeys = ['foo', 'bar'] as const;
type ExampleKeys = typeof exampleKeys; // the type you want

type ExampleKey = ExampleKeys[number];
type Example = Record<ExampleKey, boolean>;

const example: Example = {
foo: true,
bar: false,
};

Using this technique also solves a frequent problem: iterating objects in a type-safe way:

for (const key in example) {
const bool = example[key]; /*
^^^^^^^^^^^^
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Example'.
No index signature with a parameter of type 'string' was found on type 'Example'.(7053) */
}

for (const key of exampleKeys) {
const bool = example[key];
}

Interface keys from array in TypeScript

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 Topics



Leave a reply



Submit