Home > Net >  Get keys from object which uses an interface in typescript
Get keys from object which uses an interface in typescript

Time:12-09

Can I get an objects actual keys when I'm using an interface to describe the object?

Example below

interface IPerson {
    name: string;
}
interface IAddress {
    [key: string]: IPerson;
}

const personInAddressObj: IAddress= {
    someAddress1: {
        name: 'John',
    },
    someAddress2: {
        name: 'Jacob',
    }
} as const

type Keys = keyof typeof personInAddressObj;

Id want the type Keys to have the values "someAddress1 | someAddress2". If I take the interface out of "personInAddressObj", I can get the keys. However, when the interface is used, I can't get the actual keys out of the object.

CodePudding user response:

There's an open feature request for this specific use case.

For your specific example, I think you can use the new (since TypeScript 4.9) satisfies operator to have both a const assertion and type checking:

interface IPerson {
    name: string;
}

interface IAddress {
    [key: string]: IPerson;
}

const personInAddressObj = {
    someAddress1: {
        name: 'John'
    },
    someAddress2: {
        name: 'Jacob'
    }
} as const satisfies IAddress;

type Keys = keyof typeof personInAddressObj;
// ↑ inferred as "someAddress1" | "someAddress2"

Playground link

  • Related