javascript 从使用typescript中接口的对象获取键

5us2dqdw  于 2022-12-10  发布在  Java
关注(0)|答案(1)|浏览(252)

当我使用接口来描述对象时,我能得到对象的实际键吗?
示例如下

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;

我希望类型Keys的值为“someAddress1| someAddress2”。如果我将接口从“personInAddressObj”中取出,我就可以得到键。但是,当使用接口时,我无法从对象中得到实际的键。

yhived7q

yhived7q1#

对于此特定用例,有一个开放的feature request
对于您的特定示例,我认为您可以使用new(自TypeScript 4.9起)satisfies操作符来同时拥有constAssert和类型检查:

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链接

相关问题