我有以下mainObject,它包含键和值对,我想使用这个对象的值作为接口或状态的键。下面我提供了一个接口示例。
//Main Object
export const mainObject = {
NAME:'name',
AGE:'age'
}
现在我想要主对象值作为接口的键
interface sample {
'name':string //i want to achieve like this
}
//modifying the below
import mainObject from '';
interface sample {
mainObject.NAME:string //will give error, need to modify this
}
你可以这样做如果通过as const
:
mainObject
声明为运行时常量(不仅仅是mainObject
绑定,还有它包含的对象)。export const mainObject = {
NAME: "name",
AGE: "age",
} as const;
//^^^^^^^^
然后您可以通过typeof
获取该对象的类型:
type MainObjectType = typeof mainObject;
然后您可以使用该类型为Sample
创建映射类型:
type Sample = {
[key in MainObjectType[keyof MainObjectType]]: string;
};
根据您当前对mainObject
的定义,这将使以下代码有效:
const x: Sample = {
name: "something",
age: "something else",
};
操场上联系
如果您更改了mainObject
中的属性,则类型将发生变化,并且x
将需要更新以具有新属性。例如,如果我们将EXAMPLE: "example",
添加到mainObject
,但没有更新上面的x
,我们将得到x
缺少example
属性的错误-游乐场示例。