添加一个对象值作为接口或状态的键



我有以下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属性的错误-游乐场示例。

最新更新