DEV Community

Saulo Dias
Saulo Dias

Posted on

Create an Array with the Keys of an Interface

The keyof Type operator is a pretty straight forward to to so. It kind of like does to an interface the what Object.keys() does to an object.

In the example below, P can be either 'x' or 'y'.

type Point = { x: number; y: number };
type P = keyof Point;
Enter fullscreen mode Exit fullscreen mode

The example below will throw an error because 'prop4' is not a property of MyObject. Try it here.

interface MyObject {
    prop1: string;
    prop2: string;
    prop3?: string;
}

const myObject: MyObject = {
    prop1: 'prop1Value',
    prop2: 'prop2Value',
}

type K = keyof MyObject;

const someOfMyObjectKeys: K[] = ['prop1', 'prop3', 'prop4'];
Enter fullscreen mode Exit fullscreen mode

If you don't want to explicitly create a type just for that, you can use parenthesis. It's going to look like this:

const someOfMyObjectKeys: (keyof MyObject)[] = ['prop1', 'prop3', 'prop4'];
Enter fullscreen mode Exit fullscreen mode

That's it. I hope that helps!

Top comments (0)