I have the following mainObject which contains key and value pairs and I would like to use this object's value as a key to an interface or state. The following I provided an example of an interface.
//Main Object
export const mainObject = {
NAME:'name',
AGE:'age'
}
Now I want main object values as a key to an interface
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
}
CodePudding user response:
You can do that if mainObject
is declared as a runtime constant (not just the mainObject
binding, but the object it contains), via as const
:
export const mainObject = {
NAME: "name",
AGE: "age",
} as const;
//^^^^^^^^
Then you can get the type of that object via typeof
:
type MainObjectType = typeof mainObject;
Then you can use that type to create a mapped type for Sample
:
type Sample = {
[key in MainObjectType[keyof MainObjectType]]: string;
};
With your current definition of mainObject
, that would make this code valid:
const x: Sample = {
name: "something",
age: "something else",
};
If you changed the properties in mainObject
, the types would change, and x
would need to be updated to have the new properties. For example, if we added EXAMPLE: "example",
to mainObject
but didn't update x
above, we'd get an error that x
was missing the example
property — playground example.