简体   繁体   English

从 object 获取密钥,它使用 typescript 中的接口

[英]Get keys from object which uses an interface in typescript

Can I get an objects actual keys when I'm using an interface to describe the object?当我使用接口来描述 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".我希望类型键具有值“someAddress1 | someAddress2”。 If I take the interface out of "personInAddressObj", I can get the keys.如果我从“personInAddressObj”中取出接口,我可以获得密钥。 However, when the interface is used, I can't get the actual keys out of the object.但是,在使用接口时,我无法从object中取出实际的密钥。

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:对于您的具体示例,我认为您可以使用新的(自 TypeScript 4.9 起) satisfies运算符来同时进行const断言和类型检查:

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 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM